0

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.

1 Answer 1

3

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
        ;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.