【问题标题】:Summing only positive numbers in PHP array仅对 PHP 数组中的正数求和
【发布时间】:2014-09-28 12:21:34
【问题描述】:

首先,感谢您查看我的问题。

我只想使用 if,else 语句将 $numbers 中的正数相加。

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);

$total = 0;

if ($numbers < 0 {
    $numbers = 0;
}
elseif (now i want only the positive numbers to add up in the $total.)

我是一年级学生,我正在努力理解其中的逻辑。

【问题讨论】:

标签: php arrays add


【解决方案1】:

我不会给出直接的答案,但这里的方法是你需要一个简单的循环,可以是 for 或 foreach 循环,所以每次迭代你只需要检查循环中的当前数字是否大于零。

例子:

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = 0;
foreach($numbers as $number) { // each loop, this `$number` will hold each number inside that array
    if($number > 0) { // if its greater than zero, then make the arithmetic here inside the if block
        // add them up here    
        // $total 
    } else {
       // so if the number is less than zero, it will go to this block
    }
}

或者正如 michael 在 cmets 中所说,一个函数也可以用于此目的:

$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);
$total = array_sum(array_filter($numbers, function ($num){
    return $num > 0;
}));
echo $total;

【讨论】:

  • 我喜欢你向我解释这个的原因,谢谢!我现在明白其中的逻辑了。
  • @Greenie 我很高兴这能带来一些启发
  • @Greenie 顺便说一句,别忘了接受我上面的答案,第一个得到的那个,点击他答案左侧的检查。接受就是关心:)
【解决方案2】:
$numbers = array (1, 8, 12, 7, 14, -13, 8, 1, -1, 14, 7);

$total = 0;

foreach($numbers as $number)
{
  if($number > 0)
    $total += $number;
}

这循环遍历数组的所有元素(foreach = 数组中的每个数字)并检查元素是否大于0,如果是,则将其添加到$total

【讨论】:

  • foreach,离场。感谢您的时间和负担
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多