退回DatePeriod循环

时间:2016-12-21 11:57:00

标签: php

据我所知,我无法通过可变步骤设置foreach循环,所以我使用这样的for循环:

$beginDate = new DateTime( $firstday );
$endDate = new DateTime( $lastday );
$endDate = $endDate->modify( '+1 day' ); 
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($beginDate, $interval, $endDate);

$datesArray=array();
foreach($period as $dt) $datesArray[]=$dt->format('Y-m-d');

for ($dateindex=0; $dateindex < count($datesArray); $dateindex++) { 
    ...

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

是的,请使用

$interval = DateInterval::createFromDateString('-1 day');

然后计算$endDate$beginDate之间的天数差异,并在循环中使用该差异:

$beginDate = new DateTime('2016-11-28');
$endDate = new DateTime('2016-12-07');
$endDate = $endDate->modify( '+1 day' ); 
$interval = DateInterval::createFromDateString('-1 day');
$diff = $endDate->diff($beginDate);
$period = new DatePeriod($beginDate, $interval, $diff->days);

$datesArray=array();
foreach($period as $dt) $datesArray[]=$dt->format('Y-m-d');

var_dump($datesArray);