>
当您需要创建具有特定数量计算元素的集合时,Laravel的Times方法提供了优雅的解决方案。此方法对于生成序列,时间插槽,分页链接或任何需要编号迭代的场景特别有用。<!-- Syntax highlighted by torchlight.dev -->// Generate multiplication table of 5 $fives = Collection::times(10, function ($number) { return $number * 5; }); // [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
>让我们探索一个会议调度程序的实践示例,该示例生成可用的时间插槽:
<!-- Syntax highlighted by torchlight.dev --><?php namespace App\Services; use Carbon\Carbon; use Illuminate\Support\Collection; class MeetingScheduler { public function generateTimeSlots(Carbon $date, array $config = []): Collection { $startTime = $config['start_time'] ?? '09:00'; $endTime = $config['end_time'] ?? '17:00'; $duration = $config['duration'] ?? 30; $slots = $this->calculateSlotCount($startTime, $endTime, $duration); return Collection::times($slots, function ($slot) use ($date, $startTime, $duration) { $start = Carbon::parse($date->format('Y-m-d') . ' ' . $startTime) ->addMinutes(($slot - 1) * $duration); $end = $start->copy()->addMinutes($duration); return [ 'id' => $slot, 'start_time' => $start->format('H:i'), 'end_time' => $end->format('H:i'), 'formatted' => sprintf( '%s - %s', $start->format('g:i A'), $end->format('g:i A') ), 'is_available' => !$this->isSlotBooked($start, $end) ]; }); } private function calculateSlotCount($start, $end, $duration): int { $startMinutes = Carbon::parse($start)->diffInMinutes(Carbon::parse($end)); return (int) floor($startMinutes / $duration); } private function isSlotBooked(Carbon $start, Carbon $end): bool { // Check against existing bookings return false; } }
时间方法简化了生成顺序数据的过程,提供了一种干净有效的方法来创建具有计算值的收集。
以上是生成顺序的Laravel收集的详细内容。更多信息请关注PHP中文网其他相关文章!