Tom
Tom

Reputation: 781

Sort array keys by date

How can I sort this array by the date using the keys

Array
(
    [Jun '12] => 2037
    [May '12] => 4615
    [Apr '12] => 4175
    [Mar '12] => 4548
    [Feb '12] => 2758
    [Jan '12] => 3077
    [Jul '12] => 0
)

I tried uksort with this callback function with no such luck.

function datediff($a, $b) {
     strtotime($a);
    $a = date('U',strtotime($a));
    $b = date('U',strtotime($b));

    if ($a == $b) $r = 0;
    else $r = ($a > $b) ? 1: -1;

    return $r;
}

Any help is appreciated. Thanks!

Upvotes: 0

Views: 485

Answers (3)

Andy Jones
Andy Jones

Reputation: 6275

You can create a custom mapping

$date_map = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);

function date_compare($a, $b) {
  global $date_map;

  $a_month = $date_map[substr($a, 0, 3)];
  $b_month = $date_map[substr($b, 0, 3)];

  if ($a_month == $b_month) return 0;
  return ($a_month > $b_month) ? 1 : -1;
}

The use date_compare with uksort

Upvotes: 1

inVader
inVader

Reputation: 1534

datediff() always returns 0 because strtotime() does not understand the single quote in front of the 12. Thus, $a and $b are empty (and therefore equal).

So if possible you should use something like "Mar 12" as your key instead of "Mar '12". Otherwise you will have to add some sort of string manipulation in datediff before calling strtotime().

Upvotes: 0

databyss
databyss

Reputation: 6488

You need to replace the ' in your keys with "20"

http://codepad.org/sNv9QRtg

This should be a working example with some test code.

$values = array
(
    "Jun '12" => 2037,
    "May '12" => 4615,
    "Apr '12" => 4175,
    "Mar '12" => 4548,
    "Feb '12" => 2758,
    "Jan '12" => 3077,
    "Jul '12" => 0
);

//I tried uksort with this callback function with no such luck.

function datediff($a, $b) {
     strtotime($a);
    $a = date('U',strtotime(str_replace("'", "20", $a)));
    $b = date('U',strtotime(str_replace("'", "20", $b)));

    if ($a == $b) $r = 0;
    else $r = ($a > $b) ? 1: -1;

    return $r;
}

foreach($values as $key=>$val) {
    echo $key . " = " . strtotime(str_replace("'", "20", $key)) . "\n";
}

// before
print_r($values);

uksort($values, "datediff");

// after
print_r($values);

Upvotes: 0

Related Questions