-1

I found lots of answers on stackoverflow and other sites relating to arrays but they don't seem to be working with my problem. I have the following code:

Array ( 
  "-10 to -5" => Array ( [0] => 44.78 [1] => 46.86 [2] => 20.64 ) 
  "-20 to -15" => Array ( [0] => 8.01 [1] => 7.85 [2] => 21.08 ) 
  "-5 to 5" => Array ( [0] => 3.5 [1] => 0.8 [2] => 0.12 ) 
  "-15 to -10" => Array ( [0] => 43.25 [1] => 43.95 [2] => 56.02 ) 
  "-25 to -20" => Array ( [0] => 0.45 [1] => 0.54 [2] => 2.15 ) 
);

How can I sort it by its keys so that it becomes something like:

Array ( 
  "-25 to -20" => Array ( [0] => 0.45 [1] => 0.54 [2] => 2.15 ) 
  "-20 to -15" => Array ( [0] => 8.01 [1] => 7.85 [2] => 21.08 ) 
  "-15 to -10" => Array ( [0] => 43.25 [1] => 43.95 [2] => 56.02 ) 
  "-10 to -5" => Array ( [0] => 44.78 [1] => 46.86 [2] => 20.64 ) 
  "-5 to 5" => Array ( [0] => 3.5 [1] => 0.8 [2] => 0.12 ) 
);

Please suggest any solution. I tried alot and I still can't figure it out. Thanks.

JoharKhan
  • 226
  • 4
  • 7
  • Does this answer your question? [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – CBroe Mar 10 '22 at 11:11
  • Still a duplicate of the mentioned "classic", IMHO. You will just have to write a proper comparison function to use with `uksort` then. – CBroe Mar 10 '22 at 11:12

2 Answers2

1
$data = [
    '-10 to -5'  => [ 44.78, 46.86, 20.64 ],
    '-20 to -15' => [ 8.01, 7.85, 21.08 ],
    '-5 to 5'    => [ 3.5, 0.8, 0.12 ],
    '-15 to -10' => [ 43.25, 43.95, 56.02 ],
    '-25 to -20' => [ 0.45, 0.54, 2.15 ]
];

uksort($data, fn($key1, $key2) => strtok($key1, ' ') <=> strtok($key2, ' '));

print_r($data);
lukas.j
  • 6,453
  • 2
  • 5
  • 24
0

Try this:

 ksort($array, SORT_NUMERIC);