如何在php中组合数组,以便第二个数组覆盖第一个?

时间:2011-08-11 15:03:20

标签: php arrays

说我有:

$arr1 = array('green', 'yellow', 'blue', 'red');
$arr2 = array('yellow', black, white, 'red');

如果我array_merge($arr1, $arr2,)这会给出:

array(green, yellow, blue, red, yellow, black, white, red);

我想确保数组中没有重复项,请注意我没有使用数组键,只使用值。

我还缺少另一个简单的解决方案吗?

3 个答案:

答案 0 :(得分:4)

array_unique( array_merge( $arr1, $arr2 ) );

答案 1 :(得分:2)

PHP.net上有一个功能:
http://php.net/manual/en/function.array-unique.php

$unique_array = array_unique(array_merge($array1, $array2, .... ));

同样来自文档请注意,如果您打算使用密钥
"Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys"

专业提示:糟糕的命名,你应该使用比我更好的名字

答案 2 :(得分:1)

只需使用array_unique删除所有非唯一值:

$merged = array_unique(array_merge($arr1, $arr2));
相关问题