如何在不重复值的情况下组合两个数组?

时间:2022-07-26 12:20:00

I have two arrays:

我有两个数组:

array('1','2','3','4');
array('4','5','6','7');

Based on them, I'd like to generate an array that contains only unique values:

基于它们,我想生成一个只包含唯一值的数组:

array('1','2','3','4','5','6','7');

Is there any suitable function for this in PHP?

在PHP中有没有适合的功能?

2 个解决方案

#1


28  

You can use array_merge for this and then array_unique to remove duplicate entries.

您可以使用array_merge,然后使用array_unique删除重复的条目。

$a = array('1','2','3','4');
$b = array('4','5','6','7');

$c = array_merge($a,$b);

var_dump(array_unique($c));

Will result in this:

会导致这个:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [5]=>
  string(1) "5"
  [6]=>
  string(1) "6"
  [7]=>
  string(1) "7"
}

#2


8  

Yes it is array_merge() to remove dups array_unique()

是的,是array_merge()删除重复数组array_unique()

array_unique( array_merge( $array1, array2 ) );

#1


28  

You can use array_merge for this and then array_unique to remove duplicate entries.

您可以使用array_merge,然后使用array_unique删除重复的条目。

$a = array('1','2','3','4');
$b = array('4','5','6','7');

$c = array_merge($a,$b);

var_dump(array_unique($c));

Will result in this:

会导致这个:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [5]=>
  string(1) "5"
  [6]=>
  string(1) "6"
  [7]=>
  string(1) "7"
}

#2


8  

Yes it is array_merge() to remove dups array_unique()

是的,是array_merge()删除重复数组array_unique()

array_unique( array_merge( $array1, array2 ) );