1
<?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];
    } } ?>

i am trying to print in echo each student with they average score but right now i am stuck i got a warning about array to string convertion can someone give me some hint how i am suppose to do my loop.

4

3 回答 3

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

于 2013-04-17T23:33:51.027 回答
2

您正在迭代错误的数组,一旦在每个学生内部,您必须遍历“分数”,如果不是,您试图将分数数组转换为字符串:

foreach($student as $std) {
    foreach($std["score"] as $language => $score) {
        echo $score;
    }
}
于 2013-04-17T23:20:59.097 回答
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));
         }

    } 
}
于 2013-04-17T23:23:25.410 回答