Search code examples
phparraysarray-mergearray-push

How to merge two multidimensional arrays


I have two array:

$arr1 = array(
    'attributes' => array(
        'fruit'     => 'banana', 
    ),
);

$arr2 = array(
    'attributes' => array(
        'color'    => 'red', 
    ),
);

$result = array_merge($arr1, $arr2);

The result is:

Array ( [attributes] => Array ( [color] => red ) ) 

But my expected result:

Array ( [attributes] => Array ( [color] => red [fruit] => banana ) ) 

What I am doing wrong? Should I use array_merge or maybe will be better and easier just to use array_push and use only ('color' => 'red') ?


Solution

  • array_merge_recursive() is a great fit here.

    $resultArray = array_merge_recursive($arr1, $arr2);