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_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!