0
usort($childs, function($a, $b) {
    return $a['parent_id'] - $b['parent_id'];
});

Here I'm sorting it by 1 field, how can I add more fields to sort them?, Like if it was the ORDER BY field1, field2, field3 in Mysql

1

1 Answer 1

6
usort($childs, function($a, $b) {
    if ($a['field1'] == $b['field1']) {
        if ($a['field2'] == $b['field2']) {
            return $a['field3'] < $b['field3'] ? -1 : 1;
        } else {
            return 0;
        }
        return $a['field2'] < $b['field2'] ? -1 : 1;
    }
    return $a['field1'] < $b['field1'] ? -1 : 1;
});

EDIT

a slightly more generic solution (untested)

$sorts = array('field1' => 'asc', 'field2' => 'asc', 'field3' => 'asc');

usort($childs, function($a, $b) use (array $sorts = array()) {
    foreach($sorts as $field => $direction) {
        if ($a[$field] != $b[$field]) {
            if ($direction == 'asc') {
                return $a[$field] < $b[$field] ? -1 : 1;
            }
            return $a[$field] < $b[$field] ? 1 : -1;
        }
    }
    return 0;
});
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't if ($a[1] != $b[1]) return ...; if ($a[2] != $b[2]) return ... be much more readable...? :)
Why additional logic and not just return $a[..] - $b[..];?
@deceze - probably, just trying to provide a literal answer to OP's question using usort() rather than array_multisort().... and with an eye to making it more generic by passing an array (['field1' => 'asc', 'field2' => 'asc', 'field3' => 'asc']) in as well via use... though I'm not sure I have the time to make that effort at the moment
Especially in a usort callback, I wouldn't use this right-indenting nested if style. Also, if you're comparing numbers, $a - $b is fine for returning < 0, 0 and > 0. For strings I'd use strcmp, which accomplishes the same. Also see stackoverflow.com/a/22829326/476
Yes, strcmp is definitely better all round for comparing strings, when you know they're strings

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.