user849137
user849137

Reputation:

How to recursively merge two multidimensional arrays

I have two arrays, that I'm simply trying to merge together in a function:

$var1=array();
$myInputVar=array();
$var1['something']['secondary_something'][]="foo1";
$var1['something']['secondary_something'][]="foo2";
$var1['something']['secondary_something'][]="foo3";

$myInputVar['something']['secondary_something'][]="foo4";
$myInputVar['something']['secondary_something'][]="foo5";

function something(&$array_, $array_new) {
   $array = array_merge($array_ , $array_new); 

    print_r($array);//for debugging

}   
something($var1, $myInputVar);

Now that prints:

Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo1 [1] => foo2 [2] => foo3 ) ) )

When I was expecting:

Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo1 [1] => foo2 [2] => foo3 [3] => foo4 [4] => foo5) ) )

I've also tried:

$array = $array_ + $array_new;

Which still doesn't print what I'm expecting.

I have a feeling I've misunderstood the purpose of the array_merge() function, which is why its not returning the result I'm expecting it to return.

Any ideas?

Upvotes: 0

Views: 183

Answers (3)

Jack
Jack

Reputation: 5768

function something(&$array_, $array_new) {
    foreach ($array_new as $val)
        foreach ($val as $val2)
            foreach ($val2 as $val3)
                array_push($array_['something']['secondary_something'], $val3);
    print_r($array_);//for debugging
}  

Upvotes: 0

webbiedave
webbiedave

Reputation: 48897

array_merge will work from left to right. In your case:

$array_['something']['secondary_something']

will be overwritten by

$array_new['something']['secondary_something']

You could do the following:

function something(&$array_, $array_new) {
    $array = array_merge($array_ , $array_new); 
    return $array;
}

$var1['something']['secondary_something'] = something($var1['something']['secondary_something'], $myInputVar['something']['secondary_something']);

Otherwise, you'll want to create a function that is aware of the associative keys and will combine the arrays appropriately.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Try array_merge_recursive().

Upvotes: 1

Related Questions