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
Release: 2024-12-17 14:07:10
Original
307 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template