本综合指南解决了在 PHP 中对多维数组进行排序的任务。它提供了一个可重用且高度可定制的解决方案,使您能够轻松对数据进行排序。
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'] ));
该解决方案提供了在 PHP 中对多维数组进行排序的广泛功能。其灵活性和易用性使其成为各种场景下数据操作的强大工具。
以上是如何在 PHP 中对多维数组进行高效排序?的详细内容。更多信息请关注PHP中文网其他相关文章!