Home > Article > Backend Development > 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 ] ];
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);
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);
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 );
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!