Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keys in PHP array are not sorted numerically

Tags:

php

I have a PHP array with keys that contain a year and week number like so:

year-week

Using the built in ksort function it's returning them like so:

ksort($array);

2011-21
2011-3
2011-44
2011-45

Is it possible to have them sorted numerically like so:

2011-3
2011-21
2011-44
2011-45
like image 832
user1216398 Avatar asked Oct 11 '12 18:10

user1216398


2 Answers

If you are using PHP >= 5.4 use ksort($array, SORT_NATURAL);

like image 111
raidenace Avatar answered Sep 30 '22 17:09

raidenace


Use uksort to sort the keys, and in the callback use, strnatcmp.

uksort($array, function($a,$b){
    return strnatcmp($a,$b);
});
like image 31
Rocket Hazmat Avatar answered Sep 30 '22 16:09

Rocket Hazmat