array_merge & array_unique

14

在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为止,那将是很好的。

7
我认为没有更好的方法了。array_unique(array_merge($a,$b))实际上是一个相当优雅的解决方案。 - Ben Lee
2
需要注意的是,只有在键是数字或者在两个数组之间保证唯一性的情况下,array_merge 才能正常工作,否则会发生覆盖。 - Will
5个回答

26

最优雅、简洁、高效的解决方案正如原问题所提到的那样...

$ab = array_unique(array_merge($a, $b));

这个答案之前也被Ben Lee和doublejosh在评论中提到过,但是我将其作为一个真正的答案发布在这里,以便其他人发现这个问题并想知道最佳解决方案而不必阅读此页面上所有的评论。


优雅而简单,是的,但只有在数组足够大的时候,复制和排序数组才能变得更加高效。 - Ja͢ck

2
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;
}

我会选择这个作为正确答案,因为这是一个不错的方法。但是你在第5行写成了“reult”而不是“result”。另一种方法是:array_merge(array_unique(array_merge($a, $b))); 谢谢大家。 - ptmr.io
@doublejosh 在数组元素数量较少(约400个)时,这种方法会更有效率。 - Ja͢ck
1
@doublejosh 不得不处理超过10,000个项目的数组和脚本,在最大执行时间为10:00的情况下运行了9:50。好吧,那是在2011年,我很高兴我不再需要处理这种问题(新工作/更好的服务器)。 - Oliver A.
2
哦,直接在PHP中处理这么多数据!这真是太多了! - doublejosh

2
为了回答这个问题,针对一个通用解决方案,同时保留关键字和处理关联数组,我相信你会发现这个解决方案最令人满意:
/**
 * 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;
}

-1

array_merge会忽略数字键,所以在你的例子中array_merge($a, $b)会给你$ab,不需要调用array_unique()

如果你有字符串键(即关联数组),先使用array_values()

array_merge(array_values($a), array_values($b));

他想要唯一的值,因此他需要调用 array_unique - Will
它确切地说他只想要唯一的值在哪里?仅仅因为他使用了array_unique并不意味着任何事情-他自由承认他不确定该使用什么,并且描述中没有提到只想要唯一的条目。 - Stephen
@Will,你说得对,值必须是唯一的。 @Stephen:抱歉,可能有点混淆了。 解决方案是:array_merge(array_unique(array_merge($a, $b))); 因为第二个array_merge将键从0到4排序!谢谢大家! - ptmr.io
在这种情况下,您不需要两个array_merge调用 - 使用array_values调用可能是更好的选择。 - Stephen
1
原问题示例表明他正在寻找唯一的值。在调用array_merge()之前调用array_values()实际上并不起作用,因为array_merge()将重新编号数组键,因为输入数组具有数字键(请参阅array_merge() PHP文档)。 - orrd

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接