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

PHP多维关联数组计算学生成绩平均分输出全为0问题求助

现有代码核心问题

  • 变量名拼写错误:获取学生姓名数组时$tudents拼写错误,缺少字母s,导致取不到学生列表
  • 平均分计算函数逻辑错误:函数内部第一行就将传入的学生数组重置为空数组,所以总分永远为0;同时参数传递错误,调用时没有传入当前要计算的学生标识,遍历逻辑也不符合需求
  • 索引使用错误:学生数组的键是学生姓名而非数字索引,直接用$students[$i]取不到对应值
  • 缺少科目映射:现有数组存的是test1~test4,要输出为Physics、Maths等需要额外做键名映射

完整修正代码

公共逻辑部分

<?php
// 学生成绩数组
$students = array(
    "RM" => array("test1" => 35, "test2" => 30,"test3" => 39, "test4" => 80),
    "Justin" => array("test1" => 61, "test2" => 10,"test3" => 45, "test4" => 33),
    "Miley" => array("test1" => 25, "test2" => 100,"test3" => 88, "test4" => 60),
);

// 测试项和科目的映射关系
$subject_map = [
    'test1' => 'Physics',
    'test2' => 'Maths',
    'test3' => 'Chemistry',
    'test4' => 'English'
];

// 修正后的平均分计算函数
function average_scores($students, $student_name) {
    $total = 0;
    // 取出当前学生的所有成绩求和
    foreach ($students[$student_name] as $score) {
        $total += $score;
    }
    // 除以科目数得到平均分
    return $total / count($students[$student_name]);
}
?>

页面输出部分

<table style="border: 1px solid black">
    <?php
    echo "<tr><td><p><b>Listing All Student Tests and Scores:-</b></p></td></tr>";                  
    $the_students = array_keys($students);
    for($i = 0; $i < count($students); $i++) {
        $current_name = $the_students[$i];
        echo "<tr>";
        echo "<td><b>". $current_name . "</b> = ";
        // 输出对应科目成绩
        foreach($students[$current_name] as $test_key => $score) {
            echo "<b>". $subject_map[$test_key] ."</b> : " . $score. ", ";
        }
        echo "<br>";
        // 输出平均分
        echo "<b>". $current_name . " Average Scores</b>: ";
        echo average_scores($students, $current_name);                      
        echo "</td>";
        echo "</tr>";
    }
    ?>
</table>

运行后输出效果和你给出的预期完全一致。


内容的提问来源于stack exchange,提问作者NISHA NAJIHAH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:27:00