As I understand I can't set the foreach loop back by variable steps, so I use a for loop like this:
$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++) {
...
Is there a better way to do this?
yes, use
$interval = DateInterval::createFromDateString('-1 day');
then work out the difference in days between $endDate
and $beginDate
, and use that difference in your loop:
$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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.