计算 PHP 中的平均值 (Mean)

Calculating Average (Mean) in PHP

我是 PHP 的初学者,正在为一些产品实施评论聚合器系统。

我已经创建了输入字段并使用以下代码从这些字段输出结果:

{ echo '<div class="review1">Review 1: '; the_field('review1'); '</div>';}
{ echo '<div class="review2">Review 2: '; the_field('review2'); '</div>';}
{ echo '<div class="review3">Review 3: '; the_field('review3'); '</div>';}
{ echo '<div class="review4">Review 4: '; the_field('review4'); '</div>';}
{ echo '<div class="review5">Review 5: '; the_field('review5'); '</div>';}

我想使用 PHP 来计算平均值(均值),但是我用来计算它的数字设置为 5,因为这是我拥有的数字字段的总数。这是我使用的代码

{ echo (get_field('review1')+get_field('review2')+get_field('review3')+get_field('review4')+get_field('review5'))/5;}

此方法的问题在于,有时字段不包含值,因此除以的数字需要为 1、2、3 或 4,而不是 5,具体取决于具有一个值。

基本上我需要将“/5”替换为“/n”,其中“n”是具有值的字段总数。

有人可以帮忙吗?

此致, 彼得

$items = ['1','2','7','',''];

$average = calculateAverage($items);

echo $average;

function calculateAverage($items)
{
    $total = 0;
    $count = 0;

    foreach($items as $item)
    {
        if(is_numeric($item))
        {
            $total += $item;
            $count++;
        }
    }

    return $total / $count;
}

如果号码为空,则不会将号码添加到开发者

我会把值放到一个数组中,然后过滤掉non-numeric个值,然后计算平均值:

$array = [ 123, 45, null, 17, 236 ];
// $array = [ get_field('review1'), get_field('review2'), etc. ]

$values = array_filter($array, 'is_numeric');
$result = array_sum($values) / count($values);

echo $result;   // Output:   105.25