I've an array like this
Array ( [0] => Array( "destination" => "Sydney", "airlines" => "airline_1", "one_way_fare" => 100, "return_fare => 300 ), [2] => Array( "destination" => "Sydney", "airlines" => "airline_2", "one_way_fare" => 150, "return_fare => 350 ), [3] => Array( "destination" => "Sydney", "airlines" => "airline_3", "one_way_fare" => 180, "return_fare => 380 ) )
How can i sort the value by return_fare asc , one_way_fare asc ?
I tried array_multisort() but i ended up getting mixed up data..
asort only works for one dimensional array, i need to sort by two values or more, how can i achieve this like in SQL, order by field1 asc,field2 asc ?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With