计数数组子元素



我有以下多维数组:

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"
                                     ),
                );

使用array_count_values

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

相关内容

  • 没有找到相关文章

最新更新