Sorting associative multidimensions array

35 views Asked by At

Can someone please help me with sorting this array from smallest to biggest average in PHP and then it should print only smallest and biggest values in another array?

Explanation of the code will be very appreciated!

Thanks!

$students = [
  ['name' => $name1, 'surname' => $surname1, 'avg' => $avg1],
  ['name' => $name2, 'surname' => $surname2, 'avg' => $avg2],
  ['name' => $name3, 'surname' => $surname3, 'avg' => $avg3],
  ['name' => $name4, 'surname' => $surname4, 'avg' => $avg4],
  ['name' => $name5, 'surname' => $surname5, 'avg' => $avg5]
];
2

There are 2 answers

2
freezed On BEST ANSWER

uasort may provide a solution with the help of a comparison function:

<?php

$students = [
    ['name' => "name_1", 'surname' => "surname_1", 'avg' => 51],
    ['name' => "name_2", 'surname' => "surname_2", 'avg' => 42],
    ['name' => "name_3", 'surname' => "surname_3", 'avg' => 33],
    ['name' => "name_4", 'surname' => "surname_4", 'avg' => 24],
    ['name' => "name_5", 'surname' => "surname_5", 'avg' => 15]
];

function compare($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;

}    

usort($students, "compare");

// Sorted array
print_r($students);

// Smaller avg 
print_r($students[0]);

// Higher avg
print_r(array_reverse($students)[0]);
1
user9335240 On

Try using usort.

usort($students, function($a, $b) { return ($a['avg'] < $b['avg']) ? -1 :
                                            (($a['avg'] == $b['avg']) ? 0 :
                                            1 ); });

This function takes the array, and a function that compares two objects and must return

<  0 if the first  < the second
>  0 if the first  > the second
== 0 if the first == the second

If you want to print the minimum average (after the sorting)

echo $students[0]['avg'];

The maximum:

echo $students[count($students) - 1]['avg'];