Use the function usort, to sort the array, the auxiliary function cmp
defines what will be the ordering criterion and is displays only the five highest students.
$alunos = [
['nome' => "Doge", "matricula" => "M1", "altura" => 1.70 ],
['nome' => "João", "matricula" => "M2", "altura" => 1.90 ],
['nome' => "Pedro", "matricula" => "M4", "altura" => 1.50 ],
['nome' => "Mario", "matricula" => "M3", "altura" => 1.60 ],
['nome' => "A1", "matricula" => "M5", "altura" => 1.90 ],
['nome' => "A2", "matricula" => "M6", "altura" => 1.88 ]
];
function cmp($a, $b) {
return $a["altura"] < $b["altura"];
}
usort($alunos, "cmp");
for($i=0; $i<5;$i++){
echo $i .': '. $alunos[$i]['nome'] .' - '.$alunos[$i]['altura'] .'<br>';
}
Output:
0: A1 - 1.9
1: João - 1.9
2: A2 - 1.88
3: Doge - 1.7
4: Mario - 1.6
A variation of the solution would be used array_splice() to remove all items from fifth position and use a foreach.
array_splice($alunos, 5);
foreach($alunos as $item){
echo $item['nome'] .' - '. $item['altura'] .'<br>';
}
Thank you very much, very valuable reply helped me a lot!!!!
– Thiago Carvalho
Very good explanation, thank you very much!!!
– Thiago Carvalho