array_merge&array_unique
-
10-10-2019 - |
题
PHP中是否有一些数组函数,以某种方式进行array_merge,比较 值, ,忽略钥匙?我觉得 array_unique(array_merge($a, $b))
但是,我相信必须有更好的方法来做到这一点。
例如。
$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);
导致:
$ab = array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4);
请注意,我不在乎钥匙 $ab
, ,但是 会好的 如果他们登上,从0到 count($ab)-1
.
解决方案
最优雅,最简单,高效的解决方案是原始问题中提到的解决方案...
$ab = array_unique(array_merge($a, $b));
本·李(Ben Lee)和双乔什(Double Josh)的评论也提到了这个答案,但我将其发布为实际答案,以获取其他发现这个问题并想知道最好的解决方案的人的好处,而无需阅读所有评论这一页。
其他提示
function umerge($arrays){
$result = array();
foreach($arrays as $array){
$array = (array) $array;
foreach($array as $value){
if(array_search($value,$result)===false)$result[]=$value;
}
}
return $result;
}
为了回答所要求的问题,对于在保留密钥时也可以与关联阵列一起使用的一般解决方案,我相信您会发现该解决方案最令人满意:
/**
* array_merge_unique - return an array of unique values,
* composed of merging one or more argument array(s).
*
* As with array_merge, later keys overwrite earlier keys.
* Unlike array_merge, however, this rule applies equally to
* numeric keys, but does not necessarily preserve the original
* numeric keys.
*/
function array_merge_unique(array $array1 /* [, array $...] */) {
$result = array_flip(array_flip($array1));
foreach (array_slice(func_get_args(),1) as $arg) {
$result =
array_flip(
array_flip(
array_merge($result,$arg)));
}
return $result;
}
array_merge将忽略数字键,因此在您的示例中 array_merge($a, $b)
会给你的 $ab
, ,无需打电话 array_unique()
.
如果您有字符串键(即关联阵列)使用 array_values()
第一的:
array_merge(array_values($a), array_values($b));
$a = array(0 => 0, 1 => 1, 2 => 2);
$b = array(0 => 2, 1 => 3, 2 => 4);
//add any from b to a that do not exist in a
foreach($b as $item){
if(!in_array($item,$b)){
$a[] = $item
}
}
//sort the array
sort($a);
不隶属于 StackOverflow