简体   繁体   English

如何确定一个数组中另一个数组中不存在的元素?

[英]How can I determine the elements in an array that do not exist in another array?

In Ruby I can do this: 在Ruby中,我可以这样做:

fruit = ['banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava']
citrus = ['orange','lemon','lime','tangerine']
others = fruit - citrus

And others will contain an array of non-citrus fruits. others将包含一系列非柑橘类水果。

How can I do this in PHP? 如何在PHP中做到这一点?

$fruit = array('banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava');
$citrus = array('orange','lemon','lime','tangerine');
$others = # NOW WHAT ?????

Do I need to iterate over each item in $citrus and find its offset in $fruit (if it exists in that array) and then unset it, and then use array_values() to fix the array's indices? 我是否需要遍历$citrus每个项目,并在$fruit找到其偏移量(如果它存在于该数组中),然后对其进行设置,然后使用array_values()来修复该数组的索引? Or is there a simpler, less error-prone way? 还是有一种更简单,更不易出错的方式?

Please note: I'm not looking for the intersection of the arrays. 请注意:不是在寻找数组的交集 I'm looking for a complement . 我正在寻找一个补充 This was originally closed as a duplicate of a question asking the former. 最初是作为询问前一个问题的副本而关闭的。

Yes, there is array_diff() which does exactly that: 是的,有array_diff()可以做到这一点:

 $others = array_diff($fruit, $citrus);

That'll leave you with: 这将使您拥有:

Array
(
    [0] => banana
    [1] => apple
    [6] => kiwi
    [7] => mango
    [8] => guava
)

Which seems to be the expected remainder after subtracting citrus fruits from other fruits. 从其他水果中减去柑橘类水果后,这似乎是预期的剩余量。

You can just use array_diff 您可以只使用array_diff

$fruit = array('banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava');
$citrus = array('orange','lemon','lime','tangerine');
$others = array_diff($fruit, $citrus);
var_dump($others);

Output 输出量

array
  0 => string 'banana' (length=6)
  1 => string 'apple' (length=5)
  6 => string 'kiwi' (length=4)
  7 => string 'mango' (length=5)
  8 => string 'guava' (length=5)

you can use array_diff() : 您可以使用array_diff()

 $others = array_merge(array_diff($fruit, $citrus));

You would need to use array_merge to arrange the indices. 您将需要使用array_merge来安排索引。 See it in action here 这里看到它的作用

$others will contain these values: $others将包含以下值:

Array
(
    [0] => banana
    [1] => apple
    [6] => kiwi
    [7] => mango
    [8] => guava
)

this can be done by array_intersect and array_diff 这可以通过array_intersectarray_diff来完成

$filter1 = "red,green,blue,yellow";         
$parts1 = explode(',', $filter1);

$filter2 = "red,green,blue";        
$parts2 = explode(',', $filter2);


$result = array_intersect($parts1 , $parts2 );
print_r($result);

Live Example 现场例子

在此处输入图片说明

and

$result = array_diff($parts1 , $parts2 );

print_r($result);

LIVE example LIVE示例

在此处输入图片说明

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

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