php - How to sort associative array? -


i have associative array. on print_f($array_name), got this

array (         [0] => array (             [teamid] => abc             [distance] => 1.25         )         [1] => array (             [teamid] => xyz             [distance] => 0.25         )     ) 

this array want sort according distance. eg, should after sorting,

array (     [0] => array (         [teamid] => xyz         [distance] => 0.25     )     [1] => array (         [teamid] => abc         [distance] => 1.25     ) ) 

if know answer please explain or suggest me link can understand beginning. thank you.

here need do.

$a = array(array( 'teamid' => 'abc', 'distance' => 1.25 ), array( 'teamid' => 'xyz', 'distance' => 0.25 ));  $distance = array(); foreach ($a $key => $row) {     $distance[$key] = $row['distance']; } array_multisort($distance, sort_asc, $a);  print_r($a); 

this outputs

array (     [0] => array         (             [teamid] => xyz             [distance] => 0.25         )      [1] => array         (             [teamid] => abc             [distance] => 1.25         )  ) 

source example #3 sorting database results

demo

edit

as per mike's comment,

here 2 answers, 1 tells on single array should use usort(as mike's answer) , array_multisort used compare elements different arrays (or sub-arrays) @ same time.

in other answer, mike wants bench marking

usort() more concise , doesn't require extracting column array feed array_multisort(). (it less array_multisort.)

however, when repeatedly tested today on arrays of 20,000 , 10,000 representative data rows, usort() 7-15x slower array_multisort() when column random values of type int , column pre-extracted. 1 might expect, since every comparison you're comparing entire php function call optimized intrinsic code.

more bench marking notes, read full answer


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -