gpt4 book ai didi

PHP - 意外的 array_merge_recursive() 输出

转载 作者:行者123 更新时间:2023-12-04 02:52:52 24 4
gpt4 key购买 nike

我有这个代码

$a1 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
1 =>
array(1, 2, 3, 4, 5)
)
)
)
);

$a2 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
7 =>
array(6, 7, 8, 9, 10)
)
)
)
);

$results = array();
$results = array_merge_recursive($results, $a1['data']);
$results = array_merge_recursive($results, $a2['data']);
var_dump($results);

根据我对 array_merge_recursive() 的理解,我期望结果是

array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
7 =>
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10

相反,我得到了这个

array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
22 =>
array
7 =>
array
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10

22 索引从何而来?为什么输出不同?我是不是用错了函数?

最佳答案

array_merge_recursive 从与第一个数组相同的深度合并元素/数组,但如果两个数组的键都是数字索引并且它们相同,则它会附加到它。这就是您的情况。从那时起,您的数组将附加到第二级,其中通过创建索引 22 找到索引 21。要接收所需的输出,您已将索引 21 更改为字符串键,如 "x21"

php 手册中的注释

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

关于PHP - 意外的 array_merge_recursive() 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17268734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com