Reputation: 1960
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
Upvotes: 6
Views: 4612
Reputation: 11485
You can use natsort
$a = array_keys($myarray);
// $a now has
// array('2011-21', '2011-3', '2011-45', '2011-44');
natsort($a);
This prints
2011-3
2011-21
2011-44
2011-45
You can then use the $a
array as a reference to each element of the array that holds the data (in the example above $myarray
)
Upvotes: 3
Reputation: 1220
I see much simpler solutions are available, but here was my initial thought:
function cmp($a, $b) {
$comp1 = explode('-', $a);
$comp2 = explode('-', $b);
$year1 = (int) $comp1[0];
$year2 = (int) $comp2[0];
$week1 = (int) $comp1[1];
$week2 = (int) $comp2[1];
if ($year1 == $year2 && $week1 == $week2) {
return 0;
} elseif ($year1 == $year2) {
return ($week1 < $week2) ? -1 : 1;
} else {
return ($year1 < $year2) ? -1 : 1;
}
}
$array = array('2011-21', '2011-3', '2011-44', '2011-45');
uasort($array, 'cmp');
Upvotes: 0
Reputation: 1479
You'll get the result you want if you format them with a 2 digit week. Something more like 2011-03. See sprint_f().
Upvotes: 1
Reputation: 4942
You can use ksort
with natural
flag. (Only PHP 5.4+ supports)
ksort($array, SORT_NATURAL);
Upvotes: 3
Reputation: 227280
Use uksort
to sort the keys, and in the callback use, strnatcmp
.
uksort($array, function($a,$b){
return strnatcmp($a,$b);
});
Upvotes: 9