PHP sort array by two field values
Another example using the spaceship operator.
usort($data, function($a, $b) {
return $a['return_fare'] <=> $b['return_fare'] ?: $a['one_way_fare'] <=> $b['one_way_fare'];
});
array_multisort()
is the correct function, you must have messed up somehow:
// 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 volume descending, edition ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);
If you take a look at the comments at PHP's manual page for array_multisort()
, you can find a very helpful array_orderby()
function which allows you to shorten the above to just this:
$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
To avoid the looping use array_column()
(as of PHP 5.5.0):
array_multisort(array_column($data, 'return_fare'), SORT_ASC,
array_column($data, 'one_way_fare'), SORT_ASC,
$data);
In addition to array_multisort()
, which requires you to build column-arrays first, there is also usort()
which doesn't require such a thing.
usort($data, function($a, $b) {
$rdiff = $a['return_fare'] - $b['return_fare'];
if ($rdiff) return $rdiff;
return $a['one_way_fare'] - $b['one_way_fare'];
}); // anonymous function requires PHP 5.3 - use "normal" function earlier