我有一个类似
的数组$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()
这样的功能....但它不起作用
请帮我解决这个问题
答案 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
)