how to join two multidimensional arrays in php? I have two multidimensional arrays A and B. I need to join A and B to form a new array C as follows
$A = array(
array("a1"=>1,"b1"=>2,"c1"=>"A"),
array("a1"=>1,"b1"=>16,"c1"=>"Z"),
array("a1"=>3,"b1"=>8,"c1"=>"A"));
$B = array(
array("a2"=>1,"b2"=>2,"b2"=>"A"),
array("a2"=>1,"b2"=>16,"b2"=>"G"),
array("a2"=>3,"b2"=>8,"b2"=>"A"));
//join A and B to form C
$C=array(
array("a1"=>1,"b1"=>2,"c1"=>"A"),
array("a1"=>1,"b1"=>16,"c1"=>"Z"),
array("a1"=>3,"b1"=>8,"c1"=>"A"),
array("a2"=>1,"b2"=>2,"b2"=>"A"),
array("a2"=>1,"b2"=>16,"b2"=>"G"),
array("a2"=>3,"b2"=>8,"b2"=>"A"));
Merging a multidimensional array is the same as that of a simple array. It takes two arrays as input and merges them. In a multidimensional array, the index will be assigned in increment order and will be appended after the parent array. Now, let's take the example of an employee who has two addresses.
You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.
PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.
Use the array_merge
function, like this:
$C = array_merge($A, $B);
print_r($C);
When I run the above script it'll output:
Array (
[0] => Array (
[a1] => 1
[b1] => 2
[c1] => A
)
[1] => Array (
[a1] => 1
[b1] => 16
[c1] => Z )
[2] => Array (
[a1] => 3
[b1] => 8
[c1] => A
)
[3] => Array (
[a2] => 1
[b2] => A
)
[4] => Array (
[a2] => 1
[b2] => G
)
[5] => Array (
[a2] => 3
[b2] => A
)
)
Take a quick read here: http://php.net/manual/function.array-merge.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With