使用相同的键合并数组 [英] Merging arrays with the same keys

查看:70
本文介绍了使用相同的键合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个软件中,我用array_merge函数合并了两个数组.但是我需要将相同的数组(当然,具有相同的键)添加到现有数组中.

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.

问题:

 $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.

那我该如何用相同的键合并所有这些?

So how can I merge all of them with the same keys?

推荐答案

您需要使用 array_merge_recursive 而不是array_merge.当然,数组中只能有一个与'c'相等的键,但是关联的值将是同时包含34的数组.

You need to use array_merge_recursive instead of array_merge. Of course there can only be one key equal to 'c' in the array, but the associated value will be an array containing both 3 and 4.

这篇关于使用相同的键合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆