Sorting PHP Arrays by Multiple Field Values
Sorting arrays with multiple values can be tricky in PHP, but there are several approaches to achieve this. One common solution is to use the array_multisort() function.
Suppose you have an array like the one provided in the question:
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, ], ] )
To sort this array by both return_fare and one_way_fare in ascending order, you can use array_multisort() as follows:
// Obtain a list of columns foreach ($data as $key => $row) { $return_fare[$key] = $row['return_fare']; $one_way_fare[$key] = $row['one_way_fare']; } // Sort the data with return_fare descending, one_way_fare ascending array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);
This will sort the array in ascending order of return_fare, and then within equal return_fare values, it will sort in ascending order of one_way_fare.
Another option is to use the array_orderby() function, which provides a simplified syntax for sorting by multiple criteria:
$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
To avoid looping, you can also use array_column() (available in PHP 5.5.0 or later) to extract the desired columns and then use array_multisort() on those columns:
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 Field Values?. For more information, please follow other related articles on the PHP Chinese website!