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

DaImTo
  • 72,534
  • 21
  • 122
  • 346
Rustam
  • 229
  • 2
  • 11

1 Answers1

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;
});
Mark Baker
  • 199,760
  • 28
  • 325
  • 373
  • Wouldn't `if ($a[1] != $b[1]) return ...; if ($a[2] != $b[2]) return ...` be much more readable...? :) – deceze May 27 '14 at 10:53
  • 1
    Why additional logic and not just `return $a[..] - $b[..];`? – kero May 27 '14 at 10:54
  • @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 – Mark Baker May 27 '14 at 10:58
  • 1
    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 http://stackoverflow.com/a/22829326/476 – deceze May 27 '14 at 11:00
  • Yes, strcmp is definitely better all round for comparing strings, when you know they're strings – Mark Baker May 27 '14 at 11:06