添加两个关联数组以使重复值不会被覆盖的最佳方法是什么:“+”或“array_merge”?
添加两个关联数组以使重复值不会被覆盖的最佳方法是什么: +
或 array_ merge
?
我非常确定使用 +
运算符我可以添加两个关联数组,这样重复的值就不会被覆盖,但是这个 答案说的是不同的东西,所以我不确定是否这是真的。
如果您能分享一些关于如何添加两个关联数组以使重复值不被覆盖的信息,我将非常感激。
感谢您的时间和回复。
What is the best way to add two associative arrays such that duplicate values are not over written : +
or array_ merge
?
I was pretty sure that using +
operator I can add two associative arrays such that duplicate values are not over written but this Answer is saying something different and so am not sure if it is really true.
I would really appreciate if you can share some lights on how can we add two associative arrays such that duplicate values are not over written.
Appreciate your time and responses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个数组不能有多个具有相同键的键值对。因此,如果您有:
如果您组合这些数组,您只能保留组合数组的值之一。您描述的方法执行两个不同的操作:
因此,您确实需要定义组合数组时想要发生的情况。
更新
根据@davidosomething的回答,如果您执行
array_merge_recursive()
,会发生以下情况:An array can't have more than one key-value pair with the same key. So if you have:
If you combine these arrays, you only get to keep one of the values of the combined array. The methods you describe do two different things:
So you really need to define what you want to happen when you combine the arrays.
UPDATE
Based on @davidosomething's answer, here's what happens if you do
array_merge_recursive()
:你实际上想要 array_merge_recursive
如果 KEY 相同但值不同,这将创建一个数组的数组
如果发现重复的键,则 array_merge 和 union 都将丢弃其中一个值
You actually want array_merge_recursive
This creates an array of arrays if the KEY is the same but the value is different
Both array_merge and union will DISCARD one of the VALUES if a duplicate key is found
如果您想保留这两个值,则必须更改至少其中之一的密钥。也许您可以编写自己的方法来合并两个以所有键为前缀的数组。
If you want to keep both values, you have to change the key for at least one of them. Perhaps you can write your own method to merge two arrays which prefixes all keys.
如果数组具有连续的数字键,则
array_merge
将合并数组,这样就不会丢失任何值。如果开始混合字符串键,具有相同键的值将被覆盖。如果您将数组视为数组而不是映射,则 array_merge 将执行您想要的操作。array_merge
will combine the arrays such that no values are lost, provided the arrays have contiguous numeric keys. If you start mixing string keys, values with the same keys will be overwritten. If you treat your arrays as arrays and not maps, array_merge will do what you want.一张图胜过1000个字
a picture is better than 1000 words