Home >Backend Development >PHP Tutorial >How Can I Efficiently Sort Multidimensional Arrays in PHP?
This comprehensive guide addresses the task of sorting multidimensional arrays in PHP. It offers a reusable and highly customizable solution that empowers you with the ability to sort your data effortlessly.
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) { // Determine sort criteria list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1 : 1; // Project values if necessary if ($projection) { $lhs = call_user_func($projection, $first[$column]); $rhs = call_user_func($projection, $second[$column]); } else { $lhs = $first[$column]; $rhs = $second[$column]; } // Compare values; do not return if equal if ($lhs < $rhs) { return -1 * $sortOrder; } elseif ($lhs > $rhs) { return 1 * $sortOrder; } } return 0; // tiebreakers exhausted, so $first == $second }; }
// Sort $data by the "name" column using uasort $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'), ); uasort($data, make_comparer('name'));
// Sort $data by "number" and then by the zero-indexed column (ID) uasort($data, make_comparer('number', 0));
// Sort $data by "name" descending uasort($data, make_comparer(['name', SORT_DESC]));
// Sort $data by "birthday" using date_create as a projection uasort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));
// Sort $data by "number" descending and then by "birthday" ascending uasort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
This solution provides a wide range of capabilities to sort multidimensional arrays in PHP. Its flexibility and ease of use make it a powerful tool for data manipulation in various scenarios.
The above is the detailed content of How Can I Efficiently Sort Multidimensional Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!