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

How to Sort a Multidimensional Array by Multiple Columns in PHP?

DDD
DDDOriginal
2024-12-20 15:28:14876browse

How to Sort a Multidimensional Array by Multiple Columns in PHP?

How to Sort Multidimensional Arrays by Multiple Columns

Multidimensional arrays can be tricky to sort, especially when you need to consider multiple columns. Fortunately, PHP provides us with the array_multisort() function, which allows us to sort arrays based on multiple criteria.

Consider the following multidimensional 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']
]

Our goal is to sort this array first by state, then event_type, and finally by date_start. To achieve this, we'll use 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);

In versions of PHP 5.5.0 and later, we can use the array_column() function to simplify the sorting process:

array_multisort(array_column($data, 'state'), SORT_ASC,
                array_column($data, 'event_type'), SORT_ASC,
                array_column($data, 'date_start'), SORT_ASC,
                $data);

After sorting, our array will look like this:

[
    ['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']
]

The above is the detailed content of How to 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