将日期 = 今天的项目放在集合中的第一位 (Laravel)
Put items with date = today first in collection (Laravel)
我收集了所有事件 $events = App\Event::orderByDesc('start_date')->get()
。现在我想把今天的事件放在第一位,同时保持其他事件的顺序。我想我应该使用 reject()
和 prepend()
,但我无法将两者结合使用..
您可以尝试使用 partition 收集方法,如下所示:
// Create 2 collections, One for today's event and another for the other days
list($todays, $otherDays) = App\Event::orderByDesc('start_date')->get()->partition(function($event){
// NOTE: change the date comparison as necessary such as date format. I assume you use carbon here
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$events = $todays->merge($otherDays);
作为替代方案,我发现这个 post 使用了 reject 方法。对于您的情况,代码将类似于:
$filterFunc = function($event){
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$collection = App\Event::orderByDesc('start_date')->get();
$events = $collection->filter($filterFunc)->merge($collection->reject($filterFunc));
我收集了所有事件 $events = App\Event::orderByDesc('start_date')->get()
。现在我想把今天的事件放在第一位,同时保持其他事件的顺序。我想我应该使用 reject()
和 prepend()
,但我无法将两者结合使用..
您可以尝试使用 partition 收集方法,如下所示:
// Create 2 collections, One for today's event and another for the other days
list($todays, $otherDays) = App\Event::orderByDesc('start_date')->get()->partition(function($event){
// NOTE: change the date comparison as necessary such as date format. I assume you use carbon here
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$events = $todays->merge($otherDays);
作为替代方案,我发现这个 post 使用了 reject 方法。对于您的情况,代码将类似于:
$filterFunc = function($event){
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$collection = App\Event::orderByDesc('start_date')->get();
$events = $collection->filter($filterFunc)->merge($collection->reject($filterFunc));