计算数组子元素

时间:2013-04-29 15:08:50

标签: php multidimensional-array

我有以下多维数组:

Student Name Exam Result Exam Grade
David 79 1H
Brian 54 2H2
Lisa 55 2H2
Simone 58 2H2
Francis 78 1H
Shauna 53 2H2
Sean 40 Pass
Xavier 95 1H
Tom 60 2H1
Andy 66 2H2

我需要编写一个函数来计算每次的次数 在考试中取得了特定的成绩。例如,实现了3个“1H”。有什么想法吗?

$exam = array ( "names"  => array (  "David",
                                     "Brian",
                                     "Lisa",
                                     "Simone",
                                     "Francis",
                                     "Shauna",
                                     "Sean",
                                     "Xavier",
                                     "Tom",
                                       "Andy"
                                     ),
                  "results" => array ( 79,
                                       54,
                                       55,
                                       58,
                                       78,
                                       53,
                                       40,
                                       95,
                                       60,
                                       66
                                     ),
                    "grades" => array ( "1H",
                                       "2H2",
                                      "2H2",
                                       "2H2",
                                       "1H",
                                       "2H2",
                                       "Pass",
                                       "1H",
                                       "2H1",
                                       "2H1"
                                     ),
                );

1 个答案:

答案 0 :(得分:0)

使用array_count_values

 foreach(array_count_values($array['grades']) as $grade => $count){
     echo $grade.' achieved '.$count. ' times'.PHP_EOL;
 }