I」 m不會給出直接的答案,但是這裏的方法是需要一個簡單的循環,可以是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
}
}
或者像邁克爾在評論中說,功能也可以在此目的而使用:
$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;
沒有需要循環。 ['array_filter()'](http://us1.php.net/manual/en/function.array-filter.php)和['array_sum()'](http://us1.php。 net/manual/en/function.array-sum.php) – 2014-09-28 12:32:53