Associative arrays

3

I need to create an associative array with 20 students containing: enrollment, name and height. And show the top 5 students in the class, showing only student enrollment and height.

What is the best way to do this exercise?

    
asked by anonymous 11.12.2015 / 14:01

1 answer

5

Use the usort function to sort the array, the auxiliary function cmp defines which the ordering criterion and is displayed only the top five 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 use array_splice () to remove all items from the fifth position and use a foreach.

array_splice($alunos, 5);

foreach($alunos as $item){
    echo $item['nome'] .' - '. $item['altura'] .'<br>';
}
    
11.12.2015 / 14:13