如何从与其他数组元素的比较中删除数组元素?

时间:2021-04-12 13:43:57

I have two arrays. I need to remove an element from the first array when the element is included in the second array.

我有两个数组。当元素包含在第二个数组中时,我需要从第一个数组中删除一个元素。

e.g.:

例如。:

$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");

$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");

$Result = array("apple"=>"7","strawberry"=>"9");

I've used the following code but it is not working:

我使用了以下代码,但它不起作用:

foreach($Second as $key){
    $keyToDelete = array_search($key, $First);
    unset($First[$keyToDelete]);
}
print_r($First);

2 个解决方案

#1


2  

You're close!

你很亲密!

Firstly,

首先,

foreach ($Second as $key)

will only give you the value. To get the key you have to do

只会给你价值。要获得你必须要做的钥匙

foreach ($Second as $key => $value)

Loop through the $Second array and then if they key exists (use isset) in $First array remove it using unset. $Second will then be the same as $Results

循环遍历$ Second数组,然后如果它们的键存在(使用isset)在$ First数组中使用unset删除它。 $ Second将与$ Results相同

foreach ($Second as $key => $value) {
    if (isset($First[$key])) {
        unset($First[$key]);
    }
}

Alternatively, if you wanted to keep $First and $Second as they are then you can do the following:

或者,如果您想保留$ First和$ Second,那么您可以执行以下操作:

foreach ($Second as $key => $value) {
    if (!isset($First[$key])) {
        $Results[$key] = $value;
    }
}

#2


7  

Use array_diff_key - http://php.net/manual/en/function.array-diff-key.php

使用array_diff_key - http://php.net/manual/en/function.array-diff-key.php

$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");
$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");
$Result = array_diff_key($First, $Second);

#1


2  

You're close!

你很亲密!

Firstly,

首先,

foreach ($Second as $key)

will only give you the value. To get the key you have to do

只会给你价值。要获得你必须要做的钥匙

foreach ($Second as $key => $value)

Loop through the $Second array and then if they key exists (use isset) in $First array remove it using unset. $Second will then be the same as $Results

循环遍历$ Second数组,然后如果它们的键存在(使用isset)在$ First数组中使用unset删除它。 $ Second将与$ Results相同

foreach ($Second as $key => $value) {
    if (isset($First[$key])) {
        unset($First[$key]);
    }
}

Alternatively, if you wanted to keep $First and $Second as they are then you can do the following:

或者,如果您想保留$ First和$ Second,那么您可以执行以下操作:

foreach ($Second as $key => $value) {
    if (!isset($First[$key])) {
        $Results[$key] = $value;
    }
}

#2


7  

Use array_diff_key - http://php.net/manual/en/function.array-diff-key.php

使用array_diff_key - http://php.net/manual/en/function.array-diff-key.php

$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");
$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");
$Result = array_diff_key($First, $Second);