PHP将一组日期按顺序划分为多个范围



我在失眠中挣扎,不知道如何做到这一点,也不知道如何找到一个好的例子。我有一个php数组,它包含日期,比如dateArray,数组中的日期可能是按顺序排列的,也可能不是,数组中日期元素的数量因情况而异。我想从我的dateArray中制作一个新的数组数组,它将包含所有可能的日期范围,这些范围应该按照日期序列顺序构建。

例如,如果我的dateArray包含元素(dd-mm-yy(

2018-01-01,2018-01-02,2018-01-03,2018-01-05,2018-01-06

我所期望的新闻数组应该有以下结果。

0 ==> 2018-01-01,2018-01-03/
1 ==> 2018-01-05,2018-01-06

试试这个函数,它接受日期数组作为参数,它将返回日期数组中的日期范围,注意返回值是一个数组,

function getDateRangeSplitted($dates)
{
sort($dates);
$startDate  = $dates[0];
$finishDate = array_pop($dates);
// walk through the dates, breaking at gaps
foreach ($dates as $key => $date)
if (($key > 0) && (strtotime($date)-strtotime($dates[$key-1]) > 99999)) {
$result[] = array($startDate,$dates[$key-1]);
$startDate = $date;
}
// force the end
$result[] = array($startDate,$finishDate);
return $result;
}

参考:https://www.techalyst.com/links/read/122/laravel-php-split-all-possible-date-ranges-from-a-set-of-dates-by-consecutive-date-order

最新更新