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

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

问题描述

我有两个这样的数组:

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;

所有这些都可以在:http://php.net/manual/en/function.array-merge.php

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

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