<?php  $student = array(
     1 => array(
         "firstname" => "first",
         "name" => "first",
         "group" => "grp01",
         "score" => array(
             "ASP" => 86,
             "PHP" => 79,
             "JAVA" => 72,
             "HTML" => 96,
             "JAVASCRIPT" => 98,
             "VBNET" => 66
         )
     ),
     2 => array(
         "firstname" => "second",
         "name" => "second",
         "group" => "grp01",
         "score" => array(
             "ASP" => 80,
             "PHP" => 70,
             "JAVA" => 71,
             "HTML" => 92,
             "JAVASCRIPT" => 90,
             "VBNET" => 78
         )
     ),
     3 => array(
         "firstname" => "third",
         "name" => "third",
         "group" => "grp02",
         "score" => array(
             "ASP" => 88,
             "PHP" => 88,
             "JAVA" => 89,
             "HTML" => 96,
             "JAVASCRIPT" => 98,
             "VBNET" => 71
         )
     )  ); ?>

<?php

foreach($student as $std) {
    foreach($std as $key => $p){
        echo $std[$key];
    } } ?>

我试图打印回应每个学生他们的平均分数,但现在我卡住我得到一个关于数组到字符串转换的警告可以有人给我一些提示我怎么想我做我的循环。

===============>>#1 票数:2

你正在迭代错误的数组,一旦进入每个学生,你必须迭代“得分”,如果不是你试图将得分数组转换为字符串:

foreach($student as $std) {
    foreach($std["score"] as $language => $score) {
        echo $score;
    }
}

===============>>#2 票数:2 已采纳

使用PHP函数计算每个学生的平均值,四舍五入到两位数:

foreach($student as $std) {

    $avg = round(array_sum($std['score']) / count($std['score']), 2);
    echo $std['name']. ": $avg <br />";
}

看它工作: http//codepad.viper-7.com/RBINCd

===============>>#3 票数:0

当您尝试回显阵列的“得分”部分时,会出现错误。 因为它本身就是一个数组,所以不能用这种方式回声。 您将需要另一个循环来累加分数,然后获得平均值。

有点像:

foreach($student as $std) {
    foreach($std as $key => $p){

        if ( $key === 'score'){

            $avg = 0;

            foreach( $p as $score){
              $avg += $score;
            }

            $avg = ($avg/size_of($p));
         }

    } 
}

  ask by DarkVision translate from so

未解决问题?本站智能推荐: