我有一个学生“姓名”和“分数”的多维数组:
$student = array(
'Alice' => array(84, 93, 88, 100, 92, 84) ,
'bob' => array(92, 47, 68, 79, 89) ,
'charlie' => array(73, 85, 84, 69, 67, 92) ,
'denis' => array(59, 92, 83, 79, 73) ,
'eve' => array(91, 68, 85, 79, 84)
);
现在,我想找到每个学生最高“五”分的平均值:
foreach ($students as $student => $key) {
echo $student . '<br>';
arsort($key);
$value = array_slice($key, 0,5);
foreach ($value as $output){
$total += $output . '<br />';
$average = $total / count($value);
}
echo $average . '<br/>';
}
我的问题是,它不是给出所有学生的平均值,而是只给出第一个学生“Alice”的平均值。我该怎么做才能得到所有学生的平均分?
有几个问题,但只需将你内心的
foreach()
替换为:
$average = array_sum($value) / count($value);
所以:
foreach ($students as $student => $key){
echo $student . '<br>';
arsort($key);
$value = array_slice($key, 0,5);
$average = array_sum($value) / count($value);
echo $average . '<br/>';
}
如果我正确理解了问题,可以使用以下代码将每个学生的前 5 个分数添加到一个数组中,然后对该数组求平均值。
$scores = array();
foreach ($students as $student => $key){
// Sort this student's scores
arsort($key);
// Add the top 5 scores to the scores array
$scores = array_merge($scores, array_slice($key, 0,5));
}
// Average of all the top 5 scores
$average = array_sum($scores) / count($scores);
您目前采取的方法存在三个主要问题。
$average
的值N
次SUM([score1...score5]) / N
以下是每个学生前5名成绩平均分的正确实现:
$students = [
'Alice' => [84, 93, 88, 100, 92, 84],
'bob' => [92, 47, 68, 79, 89],
'charlie' => [73, 85, 84, 69, 67, 92],
'denis' => [59, 92, 83, 79, 73],
'eve' => [91, 68, 85, 79, 84],
];
$averages = array_map(function($scores) {
arsort($scores);
return array_sum(array_slice($scores, 0, 5)) / 5;
}, $students);
var_dump($averages);
/* this gives us something like ...
array(5) {
["Alice"]=>
float(91.4)
["bob"]=>
int(75)
["charlie"]=>
float(80.6)
["denis"]=>
float(77.2)
["eve"]=>
float(81.4)
}
*/
请注意,说
$average = array_sum(array_slice($scores, 0, 5)) / count($scores)
实际上是不正确,因为您只是对最高 5
分数进行平均,所以您不需要除以 count($scores)
,而是除以 5
。