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