如何根据指定列高效地排列多维数组,特别是当数据包含日期并且您需要自定义排序标准时?
引入 PHP 5.3 的增强解决方案
该解决方案具有以下几个优点:
function make_comparer() { // Normalize criteria $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) { // Comparison details list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1 : 1; // Project and compare values $lhs = $projection ? call_user_func($projection, $first[$column]) : $first[$column]; $rhs = $projection ? call_user_func($projection, $second[$column]) : $second[$column]; // Determine the comparison result if ($lhs < $rhs) { return -1 * $sortOrder; } elseif ($lhs > $rhs) { return 1 * $sortOrder; } } // Tiebreakers exhausted return 0; }; }
考虑示例data:
$data = array( array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'), array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'), array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'), array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'), );
基本排序:
多个排序列:
高级功能:
复杂用例:
按“数字”列降序排序,然后是预计的“生日”列升序:
usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
以上是如何按列(包括日期和自定义标准)对多维 PHP 数组进行高效排序?的详细内容。更多信息请关注PHP中文网其他相关文章!