You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中计算数组内question1、question2、question3的平均值

PHP计算问卷各问题平均分

需求说明

给定PHP多维数组,存储了多位受访者的question1、question2、question3得分数据,需计算三个问题各自的平均分,输出格式为:

问题1平均分 => [数值]
问题2平均分 => [数值]
问题3平均分 => [数值]

原始数组

$dragonball = [
    [
        "respondent" => "Son go",
        "question1" => "95",
        "question2" => "90",
        "question3" => "80"
    ],
    [
        "respondent" => "Son gohan",
        "question1" => "85",
        "question2" => "80",
        "question3" => "95"
    ],
    [
        "respondent" => "Son go",
        "question1" => "75",
        "question2" => "90",
        "question3" => "90"
    ]
];

实现代码

// 初始化总分与有效样本数
$totalQ1 = $totalQ2 = $totalQ3 = 0;
$sampleCount = count($dragonball);

// 遍历数组累加各题得分
foreach ($dragonball as $item) {
    $totalQ1 += (int)$item['question1'];
    $totalQ2 += (int)$item['question2'];
    $totalQ3 += (int)$item['question3'];
}

// 计算平均分(可按需调整小数位数)
$avgQ1 = $totalQ1 / $sampleCount;
$avgQ2 = $totalQ2 / $sampleCount;
$avgQ3 = $totalQ3 / $sampleCount;

// 输出结果
echo "问题1平均分 => " . $avgQ1 . "\n";
echo "问题2平均分 => " . $avgQ2 . "\n";
echo "问题3平均分 => " . $avgQ3 . "\n";

运行结果

问题1平均分 => 85
问题2平均分 => 86.666666666667
问题3平均分 => 88.333333333333

若需要固定小数位数,可使用number_format()优化输出:

echo "问题1平均分 => " . number_format($avgQ1, 2) . "\n";
echo "问题2平均分 => " . number_format($avgQ2, 2) . "\n";
echo "问题3平均分 => " . number_format($avgQ3, 2) . "\n";

优化后输出:

问题1平均分 => 85.00
问题2平均分 => 86.67
问题3平均分 => 88.33

内容的提问来源于stack exchange,提问作者E.N.D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:45:39