PHP array_merge 键顺序

标签 php arrays array-merge

执行 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/

相关文章:

java - 我在单独的类中为字符串数组实现合并排序算法时遇到问题

PHP合并数组如果为空

javascript - 如何在html中嵌入文本文件?

php - mysqli 事务仅提交一些查询

php - 每天不重叠的分钟数

python - 将 numpy 数组保存到 csv 会产生不匹配错误

php - 获取返回的行数 mysqli php

arrays - 创建后如何在 Perl6 中更改数组的大小?

javascript - 如何找到数组中的最小值,不包括第一个索引

c - 将 13 位数组合并为 unsigned char 数组