PHP手册关于array_merge的解释:
http://php.net/manual/en/function.array-merge.php
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.
If all of the arrays contain only numeric keys, the resulting array is given incrementing keys starting from zero.
意思是说,array_merge可以将多个数组的值合并。
那么下标(key)的处理是怎么搞的呢?
如果下标是字符串,那么参数中后面的数组对应下标的值会覆盖之前的值,也就是说,
array_merge(array(‘php’ => 4), array(‘php’ => 5))
返回是array(‘php’ => 5)
如果下标是数字呢,那么该值将存储到一个从0开始计数的数字下标中
也就是说,array_merge会忽略所有的数字下标,给他们赋以重新计数的下标
那么如何在合并数组时保留数字下标呢?解决的方案在手册array_merge下面的评论中:
In some situations, the union operator ( + ) might be more useful to you than array_merge. The array_merge function does not preserve numeric key values. If you need to preserve the numeric keys, then using + will do that.
用+号来代替array_merge对数组进行合并,可以保留数组的数字下标
手册中关于+号在数组运算中的解释:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
+运算符追加右侧剩下的(即左侧数组中没有的键)键与其值至左手,但是重复的键值不会被覆盖。
总结
数组合并时,要根据需要,选择array_merge或者+号,并注意其覆盖规则!
标签:PHP 数组 array_merge