如何比较两个数组并在下一个循环中从一个数组中删除匹配的元素?

时间:2022-05-25 12:08:44

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?

您还可以如何比较两个数组($A和$B),并从第一个数组中减少匹配元素,以便在数组$A上进行下一个循环?

$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);

$C = array_intersect($A,$B);  //equals (1,2,3,4)
$A = array_diff($A,$B);       //equals (5,6,7,8)

Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.

这是最简单的方法还是有办法使用另一个我没有想到的函数?我的目标是有一个可以循环的数组,取出相关内容的组(我在别处定义了这些关系),直到数组返回false。

5 个解决方案

#1


12  

You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.

你有它。只需使用array_diff或array_intersect。没有比这更简单的了。

Edit: For example:

编辑:例如:

$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);

Source

#2


2  

See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.

也看到array_unique。如果将这两个数组连接起来,它就会把所有的重复序列拉出来。

#3


2  

Dear easy and clean way

亲爱的简单干净的方式

$clean1 = array_diff($array1, $array2); 
$clean2 = array_diff($array2, $array1); 
$final_output = array_merge($clean1, $clean2);

#4


0  

Hey, even better solution: array _ uintersect. This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.

更好的解决方案是:数组_uintersect。让我们根据array_intersect对数组进行比较,然后使用回调函数对数据进行比较。

#5


0  

Try to this

尝试这个

$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
$b = array(1=>'a',6=>'b',2=>'y',3=>'z');
$c = array_intersect($a, $b);

$result = array_diff($a, $c);
print_r($result);

#1


12  

You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.

你有它。只需使用array_diff或array_intersect。没有比这更简单的了。

Edit: For example:

编辑:例如:

$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);

Source

#2


2  

See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.

也看到array_unique。如果将这两个数组连接起来,它就会把所有的重复序列拉出来。

#3


2  

Dear easy and clean way

亲爱的简单干净的方式

$clean1 = array_diff($array1, $array2); 
$clean2 = array_diff($array2, $array1); 
$final_output = array_merge($clean1, $clean2);

#4


0  

Hey, even better solution: array _ uintersect. This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.

更好的解决方案是:数组_uintersect。让我们根据array_intersect对数组进行比较,然后使用回调函数对数据进行比较。

#5


0  

Try to this

尝试这个

$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
$b = array(1=>'a',6=>'b',2=>'y',3=>'z');
$c = array_intersect($a, $b);

$result = array_diff($a, $c);
print_r($result);