如何有条件地在两个数组的对应元素之间执行减法?

How to conditionally perform subtraction between corresponding elements from two arrays?

我正在尝试从两个数组中减去值。我也尝试过 if 条件、null 值、foreach 和许多其他方法,如 array_filter,但我失败了。

$exit_price 包含:

array (
    0 => 2205,
    1 => 6680,
    2 => 50351,
    3 => 100,
    4 => 100,
    5 => 1200,
    6 => 900,
    7 => 234,
    8 => 2342,
    9 => 45654
)

$stoploss 包含:

array (
    0 => null,
    1 => null,
    2 => null,
    3 => null,
    4 => null,
    5 => null,
    6 => 145300,
    7 => null,
    8 => null,
    9 => 12222
)

如何通过从 $exit_price 中减去 $stoploss 而忽略 $stoploss 值为 null 的结果来获得以下结果?

预期结果:

array (
    6 => -144400,
    9 => 33432
)

一种方法是将两个数组传递给 array_map

在 array_map 中检查 stoploss 的当前项目是否不为空。如果不是,那就做减法。

在 array_map 之后使用 array_filter 删除空值:

$exit_price = [
    0 => 2205,
    1 => 6680,
    2 => 50351,
    3 => 100,
    4 => 100,
    5 => 1200,
    6 => 900,
    7 => 234,
    8 => 2342,
    9 => 45654
];
$stoploss = [
    0 => null,
     1 => null,
     2 => null,
     3 => null,
     4 => null,
     5 => null,
     6 => 145300,
     7 => null,
     8 => null,
     9 => 12222
];

$result = array_map(function ($x, $y) {
    if (null !== $y) {
        return $x - $y;
    }
    return null;

}, $exit_price, $stoploss);

print_r(array_filter($result, function ($z) {
    return null !== $z;
}));

Demo

您可以简单地迭代第一个数组并检查第二个数组中的相应元素是否有 null 值。如果该值不为空,则执行减法并使用当前键将差值存储在新的 "results" 数组中。

$results = [];

foreach ($stoploss as $key => $value) {
    if (!is_null($value)) {
        $results[$key] = $exit_price[$key] - $value;
    }
}