Home >Backend Development >PHP Tutorial >How to Sort a PHP Array by Multiple Fields?
Question:
How can I sort an array in PHP by two or more field values, similar to using the "ORDER BY" clause in SQL?
Example 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 ] ];
Desired Sorting:
Sort the array in ascending order of "return_fare" and then in ascending order of "one_way_fare".
Answer:
The correct PHP function to sort an array by multiple field values is array_multisort(). Here's an example of how to achieve the desired sorting:
// Extract the relevant columns $return_fare = array_column($data, 'return_fare'); $one_way_fare = array_column($data, 'one_way_fare'); // Sort the array array_multisort($return_fare, SORT_ASC, $one_way_fare, SORT_ASC, $data);
Simplified Usage with array_orderby()
You can simplify the code using the array_orderby() function from PHP's manual:
$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
Array with Arrays (Loops vs. array_column())
If your array contains arrays, you can use a loop to extract the relevant values before sorting:
$return_fare = []; $one_way_fare = []; foreach ($data as $row) { $return_fare[] = $row['return_fare']; $one_way_fare[] = $row['one_way_fare']; }
Or, if using PHP 5.5 or later, you can use array_column():
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 to Sort a PHP Array by Multiple Fields?. For more information, please follow other related articles on the PHP Chinese website!