按日期对数组进行排序,其中日期是一个月 - 年的字符串

时间:2012-08-02 11:24:32

标签: php arrays date sorting

我有一个包含Month字段的数组,该字段只是一个字符串,如下所示:

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
        )

)

如何将此数组排序为日期顺序?

感谢。

2 个答案:

答案 0 :(得分:1)

显然您需要自定义排序,因此请使用usort。这给了我们比较器。不那么漂亮的方式看起来像这样:

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);
}

示例电话:

uasort($array, 'datescompare');

您可能想要添加一些验证(如果年份可能在2000之前,如果字符串不正确等),但上述应该大致有效。

答案 1 :(得分:0)

你可以试试这个

$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);

输出

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)