0

I have an array which contains a Month field which is just a string as below:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [Month] => Jan-13
        )

    [1] => stdClass Object
        (
            [id] => 2
            [Month] => Jan-14
        )

    [2] => stdClass Object
        (
            [id] => 3
            [Month] => Jul-12
        )

)

How can I sort this array into date order?

Thanks.

4

2 回答 2

1

Obviously you need custom sorting so use usort. That leaves us with comparator. The not-that-pretty way might look like these:

function datescompare($a, $b) {
    $a = str_replace('-', ' 20', $a->Month); //changing year to full number to avoid treating it as day number
    $b = str_replace('-', ' 20', $b->Month); //same with $b

    $a = strtotime($a); //dirty, but works
    $b = strtotime($b);

    return ($a-$b);
}

example call:

uasort($array, 'datescompare');

You'd probably want to add some validation (if year might be before 2000, if the string is incorrect etc), but the above should roughly work.

于 2012-08-02T11:34:36.843 回答
0

You can try this

$array = array();
$array[0] = new stdClass();
$array[0]->id = 1 ;
$array[0]->Month = "Jul-13" ;


$array[1] = new stdClass();
$array[1]->id = 2 ;
$array[1]->Month = "Jul-14" ;

$array[2] = new stdClass();
$array[2]->id = 3 ;
$array[2]->Month = "Jul-12" ;




function cmp($a, $b) {
    $aDate = DateTime::createFromFormat("M-d",$a->Month);
    $bDate = DateTime::createFromFormat("M-d",$b->Month);
    return $aDate->getTimestamp() - $bDate->getTimestamp();
}


usort($array, "cmp");
var_dump($array);

Output

array
  0 => 
    object(stdClass)[3]
      public 'id' => int 3
      public 'Month' => string 'Jul-12' (length=6)
  1 => 
    object(stdClass)[1]
      public 'id' => int 1
      public 'Month' => string 'Jul-13' (length=6)
  2 => 
    object(stdClass)[2]
      public 'id' => int 2
      public 'Month' => string 'Jul-14' (length=6)
于 2012-08-02T11:41:11.683 回答