Return 2 values of a multidimensional associative array

2

having this array:

$materias= array (
        array("nombre"=>"Juan","Programacion"=>8,"Redes"=>7,"Dise&ntildeo Web"=>10,"Conectividad"=>9,"Idiomas"=>8),

array("nombre"=>"Sofia","Programacion"=>9,"Redes"=>10,"Dise&ntildeo Web"=>6,"Conectividad"=>8,"Idiomas"=>7),

array("nombre"=>"Santiago","Programacion"=>10,"Redes"=>10,"Dise&ntildeo Web"=>9,"Conectividad"=>7,"Idiomas"=>9),

array("nombre"=>"Maria","Programacion"=>11,"Redes"=>12,"Dise&ntildeo Web"=>10,"Conectividad"=>9,"Idiomas"=>10),

array("nombre"=>"Damian","Programacion"=>7,"Redes"=>9,"Dise&ntildeo Web"=>10,"Conectividad"=>6,"Idiomas"=>6),
);

I want to obtain the maximum grade per subject and show which student corresponds. I tried with array_columns and max and I got the maximum score but I can not show it next to that the name of who it belongs to.

    
asked by J.Saga 08.05.2016 в 23:58
source

1 answer

0

You're on the right track, this is a quick solution, without additional validations in case the array is empty or the key does not exist, nor did you specify how you will handle when two or more students have the same grade and this is the maximum , so that part can be completed:

function getBestStudent($materias, $materia)
{
    $notasMateria = array_column($materias, $materia);
    arsort($notasMateria);
    $resultado = 'Estudiante: ' . $materias[key($notasMateria)]['nombre'] . '<br>';
    $resultado .= 'Materia: ' . $materia . ' Nota: ' . $notasMateria[key($notasMateria)]; 

    return $resultado;
}

// En este caso para hallar la mejor nota (y estudiante) en Programacion
echo getBestStudent($materias, 'Programacion');
    
answered by 09.05.2016 / 01:09
source