合并两个关联数组,在按键冲突期间不会丢失元素
在一个软件中,我使用 array_merge 函数合并两个数组。但我需要将相同的数组(当然具有相同的键)添加到现有数组中。
问题:
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
array_merge($A, $B);
// result
[a] => 1 [b] => 2 [c] => 4 [d] => 5
如您所见,'c' => 3
丢失。
那么如何使用相同的键合并所有呢?
In a piece of software, I merge two arrays with array_merge
function. But I need to add the same array (with the same keys, of course) to an existing array.
The problem:
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
array_merge($A, $B);
// result
[a] => 1 [b] => 2 [c] => 4 [d] => 5
As you see, 'c' => 3
is missed.
So how can I merge all of them with the same keys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我刚刚写了这个函数,它应该可以满足你的需要,但它确实是左连接
I just wrote this function, it should do the trick for you, but it does left join
数组中的两个条目不能共享密钥,您需要更改重复项的密钥
Two entries in an array can't share a key, you'll need to change the key for the duplicate
您需要使用
array_merge_recursive
而不是array_merge
。当然,数组中只能有一个等于'c'
的键,但关联的值将是一个同时包含3
和4
的数组>。You need to use
array_merge_recursive
instead ofarray_merge
. Of course there can only be one key equal to'c'
in the array, but the associated value will be an array containing both3
and4
.尝试 array_merge_recursive
将返回
Try with array_merge_recursive
will return
如果您想按以下方式转换此数组:
那么,我的答案将是这样的:
希望这个答案有时会对某人有所帮助。
if you want to convert this array as following:
so, my answer will be like this:
hope this answer will help somebody sometime.