如何使用usort按多个字段对php数组进行排序

时间:2014-05-27 10:47:18

标签: php mysql php-5.4

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

在这里我按1字段对其进行排序,如何添加更多字段来对它们进行排序?,就好像它是Mysql中的ORDER BY field1, field2, field3

1 个答案:

答案 0 :(得分:5)

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;
});

修改

稍微更通用的解决方案(未经测试)

$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;
});