在html表格中填充一个php多维数组

lztngnrs  于 2022-11-27  发布在  PHP
关注(0)|答案(1)|浏览(195)

我被要求根据这个多维数组来填充这个html表。

$eleves=array( 
    "Z200"=>array(
        "Salima",
        "module"=>array(
            "Math"=>array("note"=>10,"cof"=>5), 
            "Physique"=>array("note"=>10,"cof"=>2),
            "Langue"=>array("note"=>10,"cof"=>2)
        )
    ), 
    "Z103"=>array(
        "Ali",
        "module"=>array(
            "Math"=>array("note"=>2,"cof"=>5), 
            "Physique"=>array("note"=>5,"cof"=>2),
            "Langue"=>array("note"=>7,"cof"=>2)
        )
    ), 
    "Z109"=>array(
        "Hind", 
        "module"=>array(
            "Math"=>array("note"=>13,"cof"=>2), 
            "Physique"=>array("note"=>13,"cof"=>2),
            "Langue"=>array("note"=>11# ,"cof"=>2)
        )
    )
);

我尝试了foreach循环。我成功地填充了第一个头表。
但是当要计算音符的时候很难计算出数值你们能帮帮我吗?

cgvd09ve

cgvd09ve1#

您需要第一个foreach来浏览$eleves。对于每个学生,您需要第二个foreach来添加所有分数并计算平均值。

function evalMoyenne ($grades) {
    $gradeSum = 0;
    $coeffCount = 0;

    foreach ( $grades as $subject => $grade ) {
        $gradeSum += $grade['note'] * $grade['cof'];
        $coeffCount += $grade['cof'];
    }

    return $gradeSum / $coeffCount;
}

foreach ( $eleves as $matricule => $row ) {
    $moyenne = evalMoyenne( $row['module'] );
    echo "<td>$matricule</td>"
    . '<td>' . $row[0] . '</td>'
    . '<td>' . $moyenne . '</td>'
}

通常,如果数组中有一个数组,则需要在foreach中有一个foreach。作为一种替代方法,如果有固定的主题计数,也可以硬编码含义计算:

$gradeSum = $row['module']['Math']['note'] * $row['module']['Math']['cof']
    + $row['module']['Physique']['note'] * $row['module']['Physique']['cof']
    + $row['module']['Langue']['note'] * $row['module']['Langue']['cof']
$cofSum = $row['module']['Math']['cof'] + $row['module']['Physique']['cof'] + $row['module']['Langue']['cof'];
$moyenne = $gradeSum / $cofSum;

相关问题