这是我的阵列:
$ar = array(
'Jan-2016' => 1,
'Feb-2016' => 2,
'Mar-2016' => 3,
'Apr-2016' => 4,
'May-2016' => 4,
'Jun-2016' => 4,
'Jul-2016' => 4,
'Aug-2016' => 4,
'Sep-2016' => 4,
'Oct-2016' => 4,
'Nov-2016' => 4,
'Dec-2016' => 4,
'Jan-2015' => 1,
'Mar-2015' => 1);
我想按月和按顺序对这个数组进行排序年。我试过下面的代码:
ksort($ar);
但我无法按照预期得到结果。
我需要结果如下所示:
$ar = array(
'Jan-2015' => 1,
'Mar-2015' => 1,
'Jan-2016' => 1,
'Feb-2016' => 2,
'Mar-2016' => 3,
'Apr-2016' => 4,
'May-2016' => 4,
'Jun-2016' => 4,
'Jul-2016' => 4,
'Aug-2016' => 4,
'Sep-2016' => 4,
'Oct-2016' => 4,
'Nov-2016' => 4,
'Dec-2016' => 4);
答案 0 :(得分:6)
uksort
是正确使用的功能:
uksort($ar, function($a1, $a2) {
$time1 = strtotime($a1);
$time2 = strtotime($a2);
return $time1 - $time2;
});
print_r($ar);
答案 1 :(得分:0)
补充:排序顺序
$sortOrder = true; // ASC
$sortOrder = false; // DESC
uksort($array, function($a, $b) use($sortOrder) {
$timeA = strtotime($a);
$timeB = strtotime($b);
return $sortOrder ? ($timeA - $timeB) : ($timeB - $timeA);
});