Home > Net >  How can I sort PHP associative array by keys that contains ranges
How can I sort PHP associative array by keys that contains ranges

Time:03-10

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.

CodePudding user response:

$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);

CodePudding user response:

Try this:

 ksort($array, SORT_NUMERIC);
  • Related