How to merge multidimensional arrays while preserving keys?

杀马特。学长 韩版系。学妹 提交于 2019-11-29 12:54:48

问题


Is there a way for these arrays

$array1 = array(
    '21-24' => array(
        '1' => array("...")
    )
);

$array2 = array(
    '21-24' => array(
        '7' => array("..."),
    )
);

$array3 = array(
    '25 and over' => array(
        '1' => array("...")
    )
);

$array4 = array(
    '25 and over' => array(
        '7' => array("...")
    )
);

to be merged which result into the array below?

array(
    '21-24' => array(
        '1' => array("..."),
        '7' => array("...")
    ),      
    '25 and over' => array(
        '1' => array("..."),
        '7' => array("...")
    )
);

NOTE:

  • I don't have control over the array structure so any solution that requires changing the structure is not what I am looking for
  • I am mainly interested in preserving the keys of the first 2 levels but a more robust solution is one that can handle all level.

I tried using array_merge_recursive() like this

$x = array_merge_recursive($array1, $array2);
$x = array_merge_recursive($x, $array3);
$x = array_merge_recursive($x, $array4);

but it resulted in

 array(
    '21-24' => array(
        '1' => array("..."),
        '2' => array("...")
    ),      
    '25 and over' => array(
        '1' => array("..."),
        '2' => array("...")
    )
);

回答1:


Have you considered array_replace_recursive()?

print_r(array_replace_recursive($array1, $array2, $array3, $array4));


来源:https://stackoverflow.com/questions/16793015/how-to-merge-multidimensional-arrays-while-preserving-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!