2013-04-17 106 views
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]; 
    } } ?> 

我試圖與他們的平均分數,但迴音每個學生打印現在我堅持我有一個關於數組串皈依警告有人可以給我一些提示我如何設想做我的循環。PHP警告數組字符串轉換循環中數組鍵

回答

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

+0

尼斯,效率+1。 – Nathan

2

你迭代錯陣列,一旦每個學生必須遍歷「分數」裏面,如果不是你試圖將比分數組轉換爲字符串:

foreach($student as $std) { 
    foreach($std["score"] as $language => $score) { 
     echo $score; 
    } 
} 
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)); 
     } 

    } 
}