如何在保留密钥的同时合并多维数组?

时间:2022-02-27 12:17:50

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

我试过像这样使用array_merge_recursive()

$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 个解决方案

#1


23  

Have you considered array_replace_recursive()?

你考虑过array_replace_recursive()吗?

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

#1


23  

Have you considered array_replace_recursive()?

你考虑过array_replace_recursive()吗?

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