Saqlain Syed Saqlain Syed - 3 months ago 22
PHP Question

Get average of each array from a multidimensional array

I have a multidimensional array of students 'name' and 'scores':

$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));


Now, I want to find the average of highest 'five' marks of each student:

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/>';
}


My problem is, instead of giving the average of all the students, it is giving the average of only first student 'Alice'. What should I do to get the average of all students?

Answer

If I understand the question correctly, the following code can be used to add each student's top 5 scores to an array, and then average that array.

$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);