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

How to Sort a Multidimensional PHP Array by Multiple Fields?

Patricia Arquette
Release: 2024-11-20 03:07:01
Original
680 people have browsed it

How to Sort a Multidimensional PHP Array by Multiple Fields?

Sorting an Array by Multiple Field Values in PHP

Problem:

You have an array with complex data structures, and you need to sort the values based on multiple field values in ascending order.

Example:

Consider the following array:

$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

You want to sort this array by first "return_fare" in ascending order and then by "one_way_fare" also in ascending order.

Solution:

To sort the array as described, you can use the array_multisort() function. However, it requires you to extract the values you want to sort into separate arrays. This can be done using array_column().

// Extract "return_fare" and "one_way_fare" into separate arrays
$return_fare = array_column($array, 'return_fare');
$one_way_fare = array_column($array, 'one_way_fare');

// Sort the array using multiple criteria
array_multisort($return_fare, SORT_ASC, $one_way_fare, SORT_ASC, $array);
Copy after login

After sorting, the $array will be modified to reflect the sorted order.

Alternative Solution:

You can also use the array_orderby() function from PHP's manual page to simplify the above code:

// Sort the array using "array_orderby"
$sorted = array_orderby($array, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
Copy after login

Note:

If you are using PHP 5.5 or higher, you can avoid the looping by using array_column() directly with array_multisort():

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

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