Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何有条件地在两个数组中的对应元素之间执行减法?_Php_Arrays_Null_Conditional_Subtraction - Fatal编程技术网

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

Php 如何有条件地在两个数组中的对应元素之间执行减法?,php,arrays,null,conditional,subtraction,Php,Arrays,Null,Conditional,Subtraction,我试图从两个数组中减去值。我还尝试了if条件、null值、foreach和许多其他方法,如array\u filter,但失败了 $exit\u price包含: array ( 0 => 2205, 1 => 6680, 2 => 50351, 3 => 100, 4 => 100, 5 => 1200, 6 => 900, 7 => 234, 8 => 2342,

我试图从两个数组中减去值。我还尝试了
if
条件、
null
值、
foreach
和许多其他方法,如
array\u filter
,但失败了

$exit\u price
包含:

array (
    0 => 2205,
    1 => 6680,
    2 => 50351,
    3 => 100,
    4 => 100,
    5 => 1200,
    6 => 900,
    7 => 234,
    8 => 2342,
    9 => 45654
)
array (
    0 => null,
    1 => null,
    2 => null,
    3 => null,
    4 => null,
    5 => null,
    6 => 145300,
    7 => null,
    8 => null,
    9 => 12222
)
$stoploss
包含:

array (
    0 => 2205,
    1 => 6680,
    2 => 50351,
    3 => 100,
    4 => 100,
    5 => 1200,
    6 => 900,
    7 => 234,
    8 => 2342,
    9 => 45654
)
array (
    0 => null,
    1 => null,
    2 => null,
    3 => null,
    4 => null,
    5 => null,
    6 => 145300,
    7 => null,
    8 => null,
    9 => 12222
)
如何通过从
$exit\u price
中减去
$stoploss
而忽略
$stoploss
值为
null
的结果来获得以下结果

预期结果:

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

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

内部数组\u映射检查
stoploss
的当前项是否为空。如果不是,那么做减法

在数组映射之后,请使用删除空值:

$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;
}));

您只需迭代第一个数组,并检查第二个数组中对应的元素是否有
null
值。如果该值不为空,则执行减法并使用当前键将差分存储在新的“结果”数组中

$results = [];

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

我敢肯定上周也有人问过同样的问题,但我找不到。无论如何,使用for循环并将值与null进行比较,如果不是,则将其添加到新数组。我不知道第一个数组在这里是如何使用的,您能提供更多信息吗?我无法通过for循环解决此问题@ChadKI只想在
$exit\u price
$stoploss
之间进行细分,并希望在数组中获得跳过空值的结果@Rosswillson这是一个课堂项目?也许看看这个帮助,也许有人会说它不够优雅,但它实际上是最好的方式继续。它比阵列地图+阵列过滤器快…@mickmackusa谢谢,你说得对。如果值不是
null
,我已经更新了array\u过滤器以返回true。