How do you efficiently arrange a multidimensional array based on a specified column, particularly when the data includes dates and you desire customized sorting criteria?
Introducing an Enhanced Solution for PHP 5.3
This solution offers several advantages:
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; }; }
Consider the sample 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'), );
Basic Sorting:
Sorting with Multiple Columns:
Advanced Features:
Complex Use Case:
Sort by the "number" column descending, followed by the projected "birthday" column ascending:
usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
The above is the detailed content of How to Efficiently Sort a Multidimensional PHP Array by Column, Including Dates and Custom Criteria?. For more information, please follow other related articles on the PHP Chinese website!