Laravel: 如何分别获取日期范围内的所有日期和日期范围内的所有日期?

Laravel: How can I get all dates between date ranges and all dates within date ranges separately?

我尝试获取 n 日期范围内的所有日期以及这些日期范围内的所有日期。

控制器:

public function index()
{
    $startDate = new Carbon('2019-11-20');
    $endDate = new Carbon('2019-11-27');
    $all_dates = array();
    while ($startDate->lte($endDate)) {
        $all_dates[] = $startDate->toDateString();
        $startDate->addDay();
    }
    return $all_dates;
}

我的输出看起来不错。这正是我需要的:

["2019-11-20","2019-11-21","2019-11-22","2019-11-23","2019-11-24","2019-11-25","2019-11-26","2019-11-27"]

我尝试了不同的方式将我的日期范围从我的数据库传递到我的函数。但它不起作用。在我的 table 中有两个重要的字段:

$query = DB::select('start_date', 'end_date')->get();

1:我怎样做才能得到与示例相同的结果?

2:如何在我的输出中忽略每个日期范围的开始日期和结束日期?我只需要日期范围内的日期。

更新:

所以我找到了第一个问题的方法。我的 table 当前有两行:

id | start_date | end_date
 1 | 2019-11-22 | 2019-11-24
 2 | 2019-11-26 | 2019-11-28

我用两个数据库查询(每个字段一个)扩展了我的工作功能,并将它们与一个循环结合起来。

public function index()
{
    $query_start_dates = Bookings::select('start_date')->get();
    $start_dates = array();
    $multiple_start_date = json_decode($query_start_dates, true);
    foreach($multiple_start_date as $single_start_date)
    $start_dates[] = implode(', ', $single_start_date);

    $query_end_dates = Bookings::select('end_date')->get();
    $end_dates = array();
    $multiple_end_date = json_decode($query_end_dates, true);
    foreach($multiple_end_date as $single_end_date)
    $end_dates[] = implode(', ', $single_end_date);

    $all_dates = array();

    foreach(array_combine($start_dates, $end_dates) as $f => $n) {
        $startDate = new Carbon($f);
        $endDate = new Carbon($n);
        while ($startDate->lte($endDate)) {
            $all_dates[] = $startDate->toDateString();
            $startDate->addDay();
        }
    }

    return $all_dates;
}

我的新输出:

["2019-11-22","2019-11-23","2019-11-24","2019-11-26","2019-11-27","2019-11-28"]

它看起来并不聪明,但它工作得很好 ;) 现在,我只需要第二个问题的解决方案。

谢谢!

因为你已经解决了你的第一个问题。我现在正在努力帮助你解决最后一个问题。同样,有很多方法可以解决它,简单的(虽然不聪明,但可以使船漂浮;))方式:

您可以简单地从日期数组中切分第一个和最后一个元素。通常,您可以使用数组移位和 pop

array_shift($all_dates);
array_pop($all_dates);

您也可以使用 array_slice,但我认为 shift 和 pop 比 slice 更好。它表现更好。