user1216398
user1216398

Reputation: 1960

Keys in PHP array are not sorted numerically

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

Answers (6)

Nikolaos Dimopoulos
Nikolaos Dimopoulos

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

Jason
Jason

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

Joshua Kaiser
Joshua Kaiser

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

Rezigned
Rezigned

Reputation: 4942

You can use ksort with natural flag. (Only PHP 5.4+ supports)

ksort($array, SORT_NATURAL);

Upvotes: 3

raidenace
raidenace

Reputation: 12836

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

Upvotes: 15

gen_Eric
gen_Eric

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

Related Questions