Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to join two multidimensional arrays in php

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"));
like image 902
nikki Avatar asked Oct 01 '13 06:10

nikki


People also ask

How do you merge multidimensional arrays?

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.

How can I merge two arrays in PHP without duplicates?

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.

What is multidimensional associative array 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.


1 Answers

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

like image 83
Joran Den Houting Avatar answered Sep 27 '22 19:09

Joran Den Houting