php 如何比较两个数组并从一个数组中删除匹配的元素以进行下一个循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/225371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two arrays and remove matching elements from one for the next loop?
提问by kevtrout
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。
回答by rg88
回答by Kalpesh Bhaliya
Dear easy and clean way
亲爱的简单干净的方式
$clean1 = array_diff($array1, $array2);
$clean2 = array_diff($array2, $array1);
$final_output = array_merge($clean1, $clean2);
回答by warren
See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.
另请参阅array_unique。如果将两个数组连接起来,它将删除所有重复项。
回答by rg88
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.
嘿,更好的解决方案:array _ uintersect。这让您可以根据 array_intersect 比较数组,但随后您可以将数据与回调函数进行比较。
回答by Ashfaq Hussain
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);

