Home > Backend Development > PHP Tutorial > How to Sort a PHP Array by Multiple Field Values?

How to Sort a PHP Array by Multiple Field Values?

Patricia Arquette
Release: 2024-12-15 05:26:12
Original
879 people have browsed it

How to Sort a PHP Array by Multiple Field Values?

Sorting PHP Arrays by Multiple Field Values

Sorting arrays with multiple values can be tricky in PHP, but there are several approaches to achieve this. One common solution is to use the array_multisort() function.

Suppose you have an array like the one provided in the question:

Array ([
        [
            'destination' => 'Sydney',
            'airlines' => 'airline_1',
            'one_way_fare' => 100,
            'return_fare' => 300,
        ],
        [
            'destination' => 'Sydney',
            'airlines' => 'airline_2',
            'one_way_fare' => 150,
            'return_fare' => 350,
        ],
        [
            'destination' => 'Sydney',
            'airlines' => 'airline_3',
            'one_way_fare' => 180,
            'return_fare' => 380,
        ],
    ]
)
Copy after login

To sort this array by both return_fare and one_way_fare in ascending order, you can use array_multisort() as follows:

// Obtain a list of columns
foreach ($data as $key => $row) {
    $return_fare[$key]  = $row['return_fare'];
    $one_way_fare[$key] = $row['one_way_fare'];
}

// Sort the data with return_fare descending, one_way_fare ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);
Copy after login

This will sort the array in ascending order of return_fare, and then within equal return_fare values, it will sort in ascending order of one_way_fare.

Another option is to use the array_orderby() function, which provides a simplified syntax for sorting by multiple criteria:

$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
Copy after login

To avoid looping, you can also use array_column() (available in PHP 5.5.0 or later) to extract the desired columns and then use array_multisort() on those columns:

array_multisort(
    array_column($data, 'return_fare'), SORT_ASC,
    array_column($data, 'one_way_fare'), SORT_ASC,
    $data
);
Copy after login

The above is the detailed content of How to Sort a PHP Array by Multiple Field Values?. 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