Laravel - GroupBy回调后的排序日期

时间:2018-05-15 16:32:20

标签: laravel sorting collections laravel-5.2

我正在创建一个集合并使用groupBy根据月份将项目组合在一起,但是在此之后,我希望它返回到升序日期顺序(Jan / Feb / Mar)。这是我在下面使用的功能;

    private function monthByMonthAgentReferrals() {
         $case = Case::where('start_date', '>', Carbon::now()->subDays(360))
                     ->where('source', 'AGENT')->get()
                     ->groupBy(function($key) {
               return Carbon::parse($key->start_date)->format('m');
         }); 
         return $case;
    }

在我显示结果时,我会以随机顺序返回月份;

Collection {#1982 ▼
  #items: array:12 [▼
    12 => Collection {#1321 ▶}
   "07" => Collection {#1322 ▶}
    10 => Collection {#1320 ▶}
   "05" => Collection {#1991 ▶}
   "06" => Collection {#1990 ▶}
   "08" => Collection {#1989 ▶}
   "01" => Collection {#1988 ▶}
    11 => Collection {#1987 ▶}
   "09" => Collection {#1986 ▶}
   "02" => Collection {#1985 ▶}
   "03" => Collection {#1984 ▶}
   "04" => Collection {#1983 ▶}
  ]
}

我如何再次按'start_date'进行排序?或者按数组键排序会更好吗?感谢。

2 个答案:

答案 0 :(得分:0)

你可以像这样使用它:

$case = Case::where('start_date', '>', Carbon::now()->subDays(360))
                 ->selectRaw('table_name.*')
                 ->where('source', 'AGENT')
                 ->groupBy(function($key) {
           return Carbon::parse($key->start_date)->format('m');
})->orderBy('start_date')->get(); 

答案 1 :(得分:0)

private function monthByMonthAgentReferrals() {
     $case = Case::where('start_date', '>', Carbon::now()->subDays(360))
                 ->where('source', 'AGENT')->get()
                 ->groupBy(function($key) {
           return Carbon::parse($key->start_date)->format('m');
     })->toArray();

     ksort($case);

     return collect($case); 
}

将集合转换为数组,使用数组上的函数ksort,然后重新收集数组。