如何根據指定列高效地排列多維數組,特別是當資料包含日期並且您需要自訂排序標準時?
引入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 = 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'), );
考慮示例data:
按「name」欄位排序: usort($data, make_comparer('name'));
依「number」欄位排序,然後依零索引列排序:usort($data, make_comparer('number', 0));
自訂投影: 將生日日期投影到時間戳以進行排序: usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));
usort($data, make_comparer( ['number', SORT_DESC], ['birthday', SORT_ASC, 'date_create'] ));
以上是如何按列(包括日期和自訂標準)對多維 PHP 陣列進行高效排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!