创建日期数组,日期之间有一系列间隔

Creating an array of dates with a sequence of intervals between days

我正在尝试使用 PHP Carbon 库在提供的开始日期和结束日期之间填充一组日期。如果日期没有特定的顺序,这将是直截了当的..

场景如下:

我需要用每周四天来填充日期数组。例如,这些日期的顺序必须是星期二作为开始日期的日期:

周二、周四、周六、周日 所以我需要一种方法来获取开始日期并在迭代到下一周之前添加 2 天然后 2 天然后 1 天。

使用 Carbon (CarbonPeriod/CarbonInterval) 可以做到这一点吗?

或者我的解决方案是否需要自定义实现?

为什么不简单地在循环中使用 DateTime::add(添加 2 天,然后 2 天,然后 1 天)?

这是documentation

Carbon 完全可以做到这一点:

// $startDate as mentioned should be a valid Carbon date pointed to Tuesday

$dates = [];
for ($currentDate = $startDate; $currentDate <= $endDate; ) {
    $dates[] = $currentDate;
    $currentDate->addDays(2);
    $dates[] = $currentDate;
    $currentDate->addDays(2);
    $dates[] = $currentDate;
    $currentDate->addDay();
}