多維數組排序可能很棘手,特別是當您需要考慮多列時。幸運的是,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中文網其他相關文章!