Sort a multidimensional associative array by a column and preserve first level keys

arrays, multidimensional-array, php, sorting

Solution

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, or as of php7 the spacehsip `<=>` operator, thx mbomb007 for the update)

Problem

I have an array that looks like this: ``` $this->wordswithdata = [ 'team1' => [ 'points' => 10, 'players' => [], ], 'team2' => [ 'points' => 23, 'players' => [] ] ]; ``` and I would like to sort the teams by the number of points each team has from highest to lowest. 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: ``` [ 0 => [ 'points' => 23, 'players' => [] ], 1 => [ 'points' => 10, 'players' => [], ] ] ``` Is there any way to sort the array without losing the teamnames as the array keys?

Original source

Related problems