Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Sort rows of a 2d array by values in 3rd column in a descending direction


I have a 2d array with rows containing an id number, a name string, and the number of times the name occurs.

I would like to sort the array by count value in a descending order.

Sample array:

[
    [1, 'Al', 3],
    [2, 'Bea', 2],
    [3, 'Chan', 1], 
    [4, 'Doug', 2],
    [5, 'Ed', 3],
    [6, 'Fey', 1],
]

Desired result:

[
    [1, 'Al', 3],
    [5, 'Ed', 3],
    [2, 'Bea', 2], 
    [4, 'Doug', 2],
    [3, 'Chan', 1],
    [6, 'Fey', 1],
]

sort() and ksort() don't do what I require.


Solution

  • Use uasort() to sort with a callback function. Example:

    function sort_callback($a, $b) {
        if ($a[2] == $b[2]) {
            return 0;
        }
    
        return ($a[2] < $b[2]) ? -1 : 1;
    }
    
    uasort($array1, 'sort_callback');