Search code examples
phparraysmultidimensional-arrayaverage

Get average of the top N values for each row from a 2d 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?


Solution

  • Several problems, but just replace your inner foreach() with:

    $average = array_sum($value) / count($value);
    

    So:

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