Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array and keep values of keys

I have an array that looks like this:

Array (     [team1] => Array         (             [points] => 10             [players] => Array                 (                      ...                 )         )      [team2] => Array         (             [points] => 23             [players] => Array                 (                      ...                 )         )      ... many more teams ) 

and I would like to sort the teams by the number of points each team has. I have tried this:

function sort_by_points($a,$b) {     if ($a['points']==$b['points']) return 0;         return ($a['points']<$b['points'])?1:-1; }  usort($this->wordswithdata, "sortbycount"); 

But that approach overrides the keys containing the teamnames and returns:

Array (     [0] => Array         (             [points] => 23             [players] => Array                 (                      ...                 )         )      [1] => Array         (             [points] => 10             [players] => Array                 (                      ...                 )         )      etc... ) 

Is there any way to sort the array without overwriting the teamnames as the array keys?

like image 280
acrmuui Avatar asked Apr 02 '13 10:04

acrmuui


1 Answers

Use the uasort function, that should keep the key => value associations intact.

(side note: you can do return $a['points'] - $b['points'] instead of the ifs)

like image 98
complex857 Avatar answered Oct 16 '22 14:10

complex857