在php中使用月份名称和年份排序数组

时间:2018-06-07 07:33:48

标签: php arrays sorting

我有一个类似

的数组
$ar =['March 2018',
      'March 2018',
      'November 2017',
      'December 2017',
      'January 2018',
      'January 2018',
      'February 2018'
     ];

我想用月份和年份对此数组进行排序。但是我无法对这个数组进行排序。

Expected Output: [
     'November 2017',
      'December 2017',
       'January 2018',
      'January 2018',
      'February 2018',
      'March 2018',
      'March 2018'
];

尝试使用像usort(), uksort()这样的功能....但它不起作用 请帮我解决这个问题

1 个答案:

答案 0 :(得分:2)

您可以使用usort并使用strtotime将字符串转换为时间。

$ar = ['March 2018',
  'March 2018',
  'November 2017',
  'December 2017',
  'January 2018',
  'January 2018',
  'February 2018'
];

usort( $ar , function($a, $b){
    $a = strtotime($a);
    $b = strtotime($b);
    return $a - $b;
});

echo "<pre>";
print_r( $ar );
echo "</pre>";

这将导致:

Array
(
    [0] => November 2017
    [1] => December 2017
    [2] => January 2018
    [3] => January 2018
    [4] => February 2018
    [5] => March 2018
    [6] => March 2018
)