感谢@mamdouh alramadan!
我写了一个辅助函数来像 MySQL 一样对数组进行排序
function arrayOrderBy(array $items, array $orderBy)
{
if (empty($items) || empty($orderBy)) {
return $items;
}
$multisortArgs = [];
foreach ($orderBy as $field => $direction) {
$columnValues = array_column($items, $field);
if (empty($columnValues)) {
continue;
}
$multisortArgs[] = $columnValues;
$multisortArgs[] = strtoupper($direction) === 'ASC' ? SORT_ASC : SORT_DESC;
}
if (empty($multisortArgs)) {
return $items;
}
$multisortArgs[] = &$items;
call_user_func_array('array_multisort', $multisortArgs);
return $items;
}
用法
$data[] = array('volume' => 67, 'edition' => 7);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 2);
$sorted = arrayOrderBy($data, ['volume' => 'desc', 'edition' => 'asc']);
print_r($sorted);
输出是:
Array
(
[0] => Array
(
[volume] => 98
[edition] => 2
)
[1] => Array
(
[volume] => 86
[edition] => 1
)
[2] => Array
(
[volume] => 86
[edition] => 6
)
[3] => Array
(
[volume] => 85
[edition] => 6
)
[4] => Array
(
[volume] => 67
[edition] => 2
)
[5] => Array
(
[volume] => 67
[edition] => 7
)
)