How Can I Sort a Multidimensional PHP Array by Multiple Fields?

DDD
Release: 2024-11-22 05:53:14
Original
905 people have browsed it

How Can I Sort a Multidimensional PHP Array by Multiple Fields?

Sorting Multidimensional Arrays by Multiple Field Values

In PHP, sorting multidimensional arrays by multiple field values can be accomplished using array_multisort().

Consider the following array:

$data = [
    [
        "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 return_fare in ascending order and one_way_fare in ascending order, use array_multisort():

// Extract specific fields into individual arrays
$return_fare = array_column($data, 'return_fare');
$one_way_fare = array_column($data, 'one_way_fare');

// Sort arrays using multiple criteria
array_multisort($return_fare, SORT_ASC, $one_way_fare, SORT_ASC, $data);

// Print sorted array
print_r($data);
Copy after login

Alternative Methods:

  • array_orderby() Function: For a concise solution, consider using the array_orderby() function, which provides a wrapper around array_multisort().
  • **array_column() with array_multisort()**: To avoid iterating over the array, use array_column()` to extract the specific field values before sorting.
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 Can I 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template