Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort array by two field values [duplicate]

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 ?

like image 260
flyclassic Avatar asked Jan 03 '11 07:01

flyclassic


1 Answers

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); 
like image 104
Tatu Ulmanen Avatar answered Sep 21 '22 23:09

Tatu Ulmanen