结合两个数组 [英] Combine two arrays

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

问题描述

我有两个数组是这样的:

I have two arrays like this:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);

array( 
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

我想这两个阵列,它不包含重复和以及保持其原有的键结合起来。例如输出应该是:

I want to combine these two array such that it does not contains duplicate and as well as keep their original keys. For example output should be:

array( 
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);

我也试过,但它正在改变其原有的键:

I have tried this but it is changing their original keys:

$output = array_unique( array_merge( $array1 , $array2 ) );

任何解决方案?

感谢

推荐答案

只需使用:

$output = array_merge($array1, $array2);

这应该解决这个问题。因为如果一个密钥(在你的例子如 '44')出现超过一次使用字符串键一个键将覆盖具有相同名称的过程使用的。因为在你的情况下,它们都具有相同的值,反正也没关系,它也将删除重复。

That should solve it. Because you use string keys if one key occurs more than one time (like '44' in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.

更新:我刚刚意识到,PHP把数字字符串键作为数字(整数),因此将这样的表现,什么手段,它重新编号的钥匙也...

Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...

一个解决方法是重新创建的键。

A workaround is to recreate the keys.

$output = array_combine($output, $output);

更新2:我总是忘了,那也有一个运营商(粗体,因为这是的真正的您正在寻找什么!:D)

Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)

$output = $array1 + $array2;

https://ideone.com/Jqhbk

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

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