$php -a
php > $data1 = ['tag' => 'div', 'classes' => [1,2,3]];
php > $data2 = ['tag' => 'section', 'classes' => [2,3,4,5,6]];
php > $result = array_merge_recursive($data1, $data2);
php > print_r($result);
Array
(
[tag] => Array
(
[0] => div
[1] => section
)
[classes] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 2
[4] => 3
[5] => 4
[6] => 5
[7] => 6
)
)
如文档所述:
PHP中是否存在一种函数,基本上可以做到相同的事情,但是不会将相同的键合并成一个数组,而是覆盖值并保留键?如果输入的数组具有相同的字符串键,则这些键的值将合并为一个数组[...]
在这种情况下,我希望得到以下结果:
Array
(
[tag] => section
[classes] => Array
(
[0] => 1
[1] => 2
[2] => 3
[5] => 4
[6] => 5
[7] => 6
)
)
关于@JustOnUnderMillions的评论:
是的,我想知道,这不是我对这种函数的期望,我期望得到我所寻找的结果。
$data2
。 - u_mulderclasses
键中的数组:如果确保值被覆盖而键保留,那么就无法得到这样的结果([0] => 1 [1] => 2 [2] => 3 [5] => 4 [6] => 5 [7] => 6)
,它会是([0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6)
。 - RomanPerekhrest