多维数组排序可能很棘手,特别是当您需要考虑多列时。幸运的是,PHP 为我们提供了 array_multisort() 函数,它允许我们根据多个条件对数组进行排序。
考虑以下多维数组:
[ ['ID' => 1, 'title' => 'Boring Meeting', 'date_start' => '2010-07-30', 'event_type' => 'meeting', 'state' => 'new-york'], ['ID' => 2, 'title' => 'Find My Stapler', 'date_start' => '2010-07-22', 'event_type' => 'meeting', 'state' => 'new-york'], ['ID' => 3, 'title' => 'Mario Party', 'date_start' => '2010-07-22', 'event_type' => 'party', 'state' => 'new-york'], ['ID' => 4, 'title' => 'Duct Tape Party', 'date_start' => '2010-07-28', 'event_type' => 'party', 'state' => 'california'] ]
我们的目标是对其进行排序数组首先按状态,然后按事件类型,最后按日期开始。为此,我们将使用 array_multisort():
$sortData = []; foreach ($data as $key => $row) { $sortData['state'][$key] = $row['state']; $sortData['event_type'][$key] = $row['event_type']; $sortData['date_start'][$key] = $row['date_start']; } array_multisort($sortData['state'], SORT_ASC, $sortData['event_type'], SORT_ASC, $sortData['date_start'], SORT_ASC, $data);
在 PHP 5.5.0 及更高版本中,我们可以使用 array_column() 函数来简化排序过程:
array_multisort(array_column($data, 'state'), SORT_ASC, array_column($data, 'event_type'), SORT_ASC, array_column($data, 'date_start'), SORT_ASC, $data);
排序后,我们的数组将如下所示:
[ ['ID' => 4, 'title' => 'Duct Tape Party', 'date_start' => '2010-07-28', 'event_type' => 'party', 'state' => 'california'], ['ID' => 2, 'title' => 'Find My Stapler', 'date_start' => '2010-07-22', 'event_type' => 'meeting', 'state' => 'new-york'], ['ID' => 1, 'title' => 'Boring Meeting', 'date_start' => '2010-07-30', 'event_type' => 'meeting', 'state' => 'new-york'], ['ID' => 3, 'title' => 'Mario Party', 'date_start' => '2010-07-22', 'event_type' => 'party', 'state' => 'new-york'] ]
以上是如何在 PHP 中按多列对多维数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!