执行 array_merge 时数组数组中键的顺序是否重要,即下面第二个数组中的键是否会覆盖第一个数组中的键:
array1 = array('username' => 'abc', 'level' => 'admin', 'status' => 'active');
array2 = array('level' => 'root', 'status' => 'active', 'username' => 'bcd');
?还是两个数组中键的顺序必须相同?
最佳答案
manual陈述这个问题的答案:
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
是的,如果第二个数组包含一些相同的键,第二个数组中的键将覆盖第一个数组中的键。
$array1 = array('username' => 'abc', 'level' => 'admin', 'status' => 'active');
$array2 = array('level' => 'root', 'status' => 'active', 'username' => 'bcd');
$new = array_merge($array1, $array2);
print_r($new);
输出:
Array
(
[username] => bcd
[level] => root
[status] => active
)
因此您可以看到第二个数组中的键覆盖了第一个数组中的相同键;每个数组中键的顺序无关紧要。
关于PHP array_merge 键顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11641822/