如何合并两个多维数组

时间:2022-07-26 12:19:54

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') ?

我做错了什么?我应该使用array_merge,还是仅仅使用array_push并且只使用('color' => 'red')会更好更简单?

2 个解决方案

#1


6  

array_merge_recursive() is a great fit here.

array_merge_recursive()非常适合这里。

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

#2


-2  

try this:

试试这个:

$result = array('attributes' => array_merge($arr1['attributes'], $arr2['attributes']));
print_r($result);

#1


6  

array_merge_recursive() is a great fit here.

array_merge_recursive()非常适合这里。

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

#2


-2  

try this:

试试这个:

$result = array('attributes' => array_merge($arr1['attributes'], $arr2['attributes']));
print_r($result);