首页 > 解决方案 > 在 array_sum 中计算时,如果数组中的值为空,则使用 $stoploss 作为 `$exit_price

问题描述

我正在尝试声明:如果数组中的计算 为空,则使用 $stoploss 作为array_sum$stoploss$exit_price

在下面的声明中:

$expectancy_a = array_sum(($exit_price - ($stoploss)))/$number_trades;

$stoploss具有以下值:

array:10 [▼
  0 => null
  1 => null
  2 => 425
  3 => null
  4 => 77
]

我怎么能在那个语句中说,如果 $stoploss 有空值,那么将 $exit_price 作为 $stoploss。

我厌倦了if条件:

if (in_array(null, $stoploss, true)) {
$r_multiple[] = ($exit_price - $entry_price) / ($entry_price - $stoploss);
}

标签: phplaravellaravel-5

解决方案


您应该考虑使用使用空合并的闭包映射 $stoploss:

$corrected = array_map(function($value) use ($exit_price) {
    return $value ?? $exit_price;
}, $stoploss);

这会将所有空值转换为 $stoploss 数组中的 $exit_price。


推荐阅读