如何在 PHP 中对多维数组进行排序
介绍 PHP 5.3 的通用解决方案
实现:
function make_comparer() { // Normalize criteria up front $criteria = func_get_args(); foreach ($criteria as $index => $criterion) { $criteria[$index] = is_array($criterion) ? array_pad($criterion, 3, null) : array($criterion, SORT_ASC, null); } return function($first, $second) use (&$criteria) { foreach ($criteria as $criterion) { list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1 : 1; if ($projection) { $lhs = call_user_func($projection, $first[$column]); $rhs = call_user_func($projection, $second[$column]); } else { $lhs = $first[$column]; $rhs = $second[$column]; } if ($lhs < $rhs) { return -1 * $sortOrder; } elseif ($lhs > $rhs) { return 1 * $sortOrder; } } return 0; // tiebreakers exhausted }; }
高级功能:
(1) 多重排序列:
usort($data, make_comparer('number', 'name'));
(2) 反向排序:
usort($data, make_comparer(['name', SORT_DESC]));
(3) 自定义投影:
usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));
(4) 组合特点:
usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
优点:
以上是如何使用灵活且可重用的函数在 PHP 中对多维数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!