如何从PHP中减去数组中的值?

时间:2021-12-10 13:43:14

I am trying to "subtract" the values of an array in php. I used array_diff but it doesn't seem to work for more than one value.

我试图在php中“减去”数组的值。我使用了array_diff但它似乎不适用于多个值。

<?php

    $array1 = array(1,3,7,10,7);
    $array2 = array(1,7);

    $result=array_diff($array1,$array2);
    print_r($result);

?>

//Output//
Array ( [1] => 3 [3] => 10 )

What I would like to do is return 3,7,10 instead of excluding all 7's. Thanks in advance!

我想做的是返回3,7,10而不是排除所有7个。提前致谢!

2 个解决方案

#1


1  

Try:

尝试:

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);

foreach( $removals as $remove ) {
    foreach( $array1 as $key => $value ) {
        if ($value === $remove ) {
            unset($array1[ $key ]);
            break;
        }
    }
}

print_r($array1); // Array ( [1] => 3 [3] => 10 [4] => 7 )
sort($array1)
print_r($array1); // Array ( [0] => 3 [1] => 7 [2] => 10 )

#2


0  

based on thelastshadows post but shorter and may faster because only one foreach

基于thelastshadows post但更短,可能更快,因为只有一个foreach

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);
foreach( $removals as $remove ) {
    unset($array1[array_search($remove,$array1)]);
}
sort($array1);
print_r($array1);

#1


1  

Try:

尝试:

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);

foreach( $removals as $remove ) {
    foreach( $array1 as $key => $value ) {
        if ($value === $remove ) {
            unset($array1[ $key ]);
            break;
        }
    }
}

print_r($array1); // Array ( [1] => 3 [3] => 10 [4] => 7 )
sort($array1)
print_r($array1); // Array ( [0] => 3 [1] => 7 [2] => 10 )

#2


0  

based on thelastshadows post but shorter and may faster because only one foreach

基于thelastshadows post但更短,可能更快,因为只有一个foreach

$array1 = array(1,3,7,10,7);
$removals = Array(1,7);
foreach( $removals as $remove ) {
    unset($array1[array_search($remove,$array1)]);
}
sort($array1);
print_r($array1);