Home  >  Article  >  Backend Development  >  How Can I Sort a Multidimensional PHP Array by Multiple Fields?

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

DDD
DDDOriginal
2024-11-22 05:53:14906browse

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
    ]
];

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);

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);

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!

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