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


Sort array by date where the date is a string of just month-year

我有一个数组,它包含一个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
        )
)

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

谢谢。

显然您需要自定义排序,所以请使用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年之前,如果字符串不正确等),但以上内容应该大致有效。

你可以试试这个

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