我有一个数组,我需要得到数组中所有EVEN数字的平均值,我已经尝试过了,但仍然不起作用。
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
for ($q = 0; $q < count($aReeks); $q++)
{
{
if ($aReeks[$q] % 2 == 0)
$totaaleven = array_sum($aReeks[$q]) / count($aReeks[$q]);
}
}
echo $totaaleven
我认为这应该适用于
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
$evenSum = 0;
$evenCount = 0;
foreach($aReeks as $number) {
if($number % 2 == 0) {
$evenSum = $evenSum + $number;
$evenCount++;
}
}
$average = $evenSum / $evenCount;
您可以使用array_filter
为偶数过滤数组,并简单地将sum除以count,如下所示:
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
$evenNos = array_filter($aReeks, function($value) {
return !($value%2);
});
echo array_sum($evenNos)/count($evenNos);