Search code examples
phparrayssortingarray-multisort

Sorting PHP array by 3 values


I need to sort an array by three values. Here's a basic setup of how the array is setup:

$arr = array(
    '1' => array(
        'start' => '1234',
        'mh' => '12',
        'status' => '1'
    ),
    '2' => array(
        'start' => '9874',
        'mh' => '3',
        'status' => '9'
    ),
    '3' => array(
        'start' => '5678',
        'mh' => '6',
        'status' => '2'
    )
);

Currently, I've only had to sort by 2 values, which array_multisort came in handy for. Now I need to sort by all three values in this order: Status (low) -> Start (low) -> MH (high). Meaning that the lowest status is first, then the lowest start, then the highest MH.

Any help would be appreciated.


Solution

  • A general solution for sorting by multiple columns:

    usort($arr,function($a,$b) {
        return ($a['status'] - $b['status']) // status ascending
            ?: ($a['start'] - $b['start']) // start ascending
            ?: ($b['mh'] - $a['mh']) // mh descending
            ;
    });