usort($childs, function($a, $b) {
return $a['parent_id'] - $b['parent_id'];
});
在这里我按1字段对其进行排序,如何添加更多字段来对它们进行排序?,就好像它是Mysql中的ORDER BY field1, field2, field3
答案 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;
});