Php 使用laravel集合对月份数组进行排序

Php 使用laravel集合对月份数组进行排序,php,laravel,sorting,collections,closures,Php,Laravel,Sorting,Collections,Closures,我的数组是 $array = [ 1 => 0 2 => 0 3 => 0 4 => 0 5 => 0 6 => 0 7 => 2 8 => 0 9 => 0 10 => 1 11 => 0 12 => 1 ]; 因此,我希望它是 $array = [ 10 => 1 11 => 0 12 => 1 1 => 0 2 => 0 3 => 0 4 =&

我的数组是

$array = [
 1 => 0
 2 => 0
 3 => 0
 4 => 0
 5 => 0
 6 => 0
 7 => 2
 8 => 0
 9 => 0
 10 => 1
 11 => 0
 12 => 1
];
因此,我希望它是

$array = [
 10 => 1
 11 => 0
 12 => 1
 1 => 0
 2 => 0
 3 => 0
 4 => 0
 5 => 0
 6 => 0
 7 => 2
 8 => 0
 9 => 0
];
我现在的逻辑是

$sorted = collect($array)
  ->sortBy(function ($count, $month) {
    return $month <= 9;
  });
$sorted=collect($array)
->排序(功能($count,$month){

return$month您可以这样做:

$sorted = collect($array)->sortBy(function ($count, $month) {
    $currentMonth = (int) \Carbon\Carbon::now()->month;

    return ($month + (12 - $currentMonth - 1)) % 12;
});

您可以从php函数中

krsort()

krsort可以根据键按降序对关联数组进行排序

ksort($array);

正如我所写的,我希望第9个月是最后一个键。你能再举一些例子说明结果吗?当有20个时会发生什么?它应该排在前面吗?只有12个月;)@nrkz所以,如果是5月(5),数组应该看起来像[6,7,8,9,10,11,12,1,2,3,4,5]?kerbholz完全正确;)完美;)谢谢!->sortBy(函数($count,$month){return($month+(12-Carbon::now()->month-1))%12;});不客气。我一定会按照你的建议使用
->month
。我记得我只使用了
->格式('n')
,没有费心查找有关碳的文档。我已经更新了我的答案。