2011-08-11 52 views
4

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

$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); 

我希望确保在数组中没有重复,注意,我没有使用数组键,只值。

有没有另一个简单的解决方案,我失踪了?

回答

4
array_unique(array_merge($arr1, $arr2)); 
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"

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

1

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

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