Sorting Multidimensional Arrays by Multiple Columns
Sorting a multidimensional array can be a challenging task, especially when considering multiple criteria. Fortunately, PHP offers an elegant solution in the form of the array_multisort function.
To sort a multidimensional array, we need to extract the required columns and pass them to array_multisort. Each column is sorted independently, with the sort order specified as SORT_ASC or SORT_DESC.
For instance, given the following input array:
$array = [ ['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'] ];
To sort by state, then event_type, and finally date_start, we would use the following code:
# extract columns $state = array_column($array, 'state'); $event_type = array_column($array, 'event_type'); $date_start = array_column($array, 'date_start'); # sort by state desc, event_type asc, date_start asc array_multisort($state, SORT_DESC, $event_type, SORT_ASC, $date_start, SORT_ASC, $array);
PHP 5.5.0 introduces a simplified syntax using array_column:
array_multisort( array_column($array, 'state'), SORT_DESC, array_column($array, 'event_type'), SORT_ASC, $array );
As a result, the sorted array looks like:
[ ['ID' => 4, 'title' => 'Duct Tape Party', 'date_start' => '2010-07-28', 'event_type' => 'party', 'state' => 'california'], ['ID' => 3, 'title' => 'Mario Party', 'date_start' => '2010-07-22', 'event_type' => 'party', 'state' => 'new-york'], ['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'], ];
By utilizing array_multisort, we effectively sorted the multidimensional array based on multiple columns, providing a flexible and powerful solution for data organization and retrieval.
The above is the detailed content of How can I sort a multidimensional array in PHP by multiple columns using `array_multisort`?. For more information, please follow other related articles on the PHP Chinese website!