dt888999
2018-02-22 11:15 阅读 154
已采纳

如何合并两个多维数组

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dtbl1231 dtbl1231 2018-02-22 11:19

    array_merge_recursive() is a great fit here.

    $resultArray = array_merge_recursive($arr1, $arr2);
    
    点赞 评论 复制链接分享
  • duanbi3786 duanbi3786 2018-02-22 11:27

    try this:

    $result = array('attributes' => array_merge($arr1['attributes'], $arr2['attributes']));
    print_r($result);
    
    点赞 评论 复制链接分享

相关推荐