Home >Backend Development >PHP Tutorial >How Can I Sort a Multidimensional Array by Multiple Columns in PHP?

How Can I Sort a Multidimensional Array by Multiple Columns in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 14:07:10308browse

How Can I Sort a Multidimensional Array by Multiple Columns in PHP?

Sorting Multidimensional Arrays by Multiple Columns

Sorting multidimensional arrays by multiple columns can be a challenging task. However, PHP provides an array of functions that make it relatively straightforward.

One such function is array_multisort(). This function allows you to sort an array by multiple criteria simultaneously. To use array_multisort(), you must first create an array of sort columns and their corresponding data.

Here's an example:

<?php
$mylist = array(
    array('ID' => 1, 'title' => 'Boring Meeting', 'date_start' => '2010-07-30', 'event_type' => 'meeting', 'state' => 'new-york'),
    array('ID' => 2, 'title' => 'Find My Stapler', 'date_start' => '2010-07-22', 'event_type' => 'meeting', 'state' => 'new-york'),
    array('ID' => 3, 'title' => 'Mario Party', 'date_start' => '2010-07-22', 'event_type' => 'party', 'state' => 'new-york'),
    array('ID' => 4, 'title' => 'Duct Tape Party', 'date_start' => '2010-07-28', 'event_type' => 'party', 'state' => 'california')
);

# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k => $v) {
    $sort['state'][$k] = $v['state'];
    $sort['event_type'][$k] = $v['event_type'];
    $sort['date_start'][$k] = $v['date_start'];
}

# sort by state asc, event_type desc, and date_start asc
array_multisort($sort['state'], SORT_ASC, $sort['event_type'], SORT_DESC, $sort['date_start'], SORT_ASC, $mylist);

print_r($mylist); // print the sorted array

?php>

As of PHP 5.5.0, you can use the following simplified syntax:

<?php
array_multisort(array_column($mylist, 'state'), SORT_ASC,
                array_column($mylist, 'event_type'), SORT_DESC,
                array_column($mylist, 'date_start'), SORT_ASC,
                $mylist);
?php>

The $mylist array will now be sorted by the specified columns in the desired order.

The above is the detailed content of How Can I Sort a Multidimensional Array by Multiple Columns in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn