Associative arrays

Asked

Viewed 110 times

3

People work for a while as a designer/front-end, but only now I’m studying php and I have a question.

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

What is the best way to accomplish this exercise?

1 answer

5


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!!!!

  • Very good explanation, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.