简体   繁体   English

PHP - 比较两个数组,如果有重复项删除所有匹配项

[英]PHP - Compare two arrays and if there are duplicates remove all matches

I have two arrays:我有两个数组:

foo
bar
baz

and

foo
baz

I'd like to compare these two arrays and if there are matches, remove both matches (not just duplicates) so I end up with an array like this:我想比较这两个数组,如果有匹配项,删除两个匹配项(不仅仅是重复项),所以我最终得到一个这样的数组:

bar

I know that array 1 will always contain foo , bar , and baz and that array 2 will always contain foo and baz .我知道数组 1 将始终包含foobarbaz ,而数组 2 将始终包含foobaz The entries in the array won't always be in the same order but the contents will stay the same.数组中的条目不会总是以相同的顺序排列,但内容将保持不变。

Instead of comparing the two arrays I could do something like the solution of 16153948 , but that would require me to use a (almost) duplicate line for each match I want to remove since the entries are fairly unrelated (can't use regex), which doesn't seem like a good solution.而不是比较两个数组,我可以做一些类似于16153948的解决方案,但这需要我为我想删除的每个匹配项使用(几乎)重复的行,因为条目相当不相关(不能使用正则表达式),这似乎不是一个好的解决方案。

You could get the differences of both arrays using array_diff and then merge them using array_merge :您可以使用array_diff获取两个数组的差异,然后使用array_merge合并它们:

$res = array_merge(array_diff($a, $b), array_diff($b, $a));
print_r($res);

Php demo php 演示

Output输出

Array
(
    [0] => bar
)

Php demo with more different values.具有更多不同值的PHP 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM