这与这里提出的另一个问题有关,这个问题很完美,但我反过来需要它,你知道如何实现这个吗?
原始问题在这里 I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
答案 0 :(得分:4)
您可以使用iterator_to_array + array_reverse方法:
foreach (array_reverse(iterator_to_array($period)) as $day) {...}
答案 1 :(得分:0)
使用PHP 5.5生成器
function period($begin, $interval, $end) {
if ($begin < $end) {
while ($begin <= $end) {
yield $begin;
$begin->add($interval);
}
}else {
while ($end <= $begin) {
yield $begin;
$begin->sub($interval);
}
}
}
$interval = new \DateInterval('P1D');
$begin = new \DateTime( '2010-05-10' );
$end = new \DateTime( '2010-05-01' );
foreach (period($begin, $interval, $end) as $dt) {
echo $dt->format( "l Y-m-d H:i:s" ), PHP_EOL;
}
$begin = new \DateTime( '2010-05-01' );
$end = new \DateTime( '2010-05-10' );
foreach (period($begin, $interval, $end) as $dt) {
echo $dt->format( "l Y-m-d H:i:s" ), PHP_EOL;
}
答案 2 :(得分:-1)
是的,您可以以日期格式的反向使用它
$begin = new DateTime( '2010-05-01' );
$end = new DateTime( '2010-05-10' );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
$reverse = array_reverse(iterator_to_array($period)); //sorts in descending order...
foreach ( $reverse as $dt )
echo $dt->format( "l Y-m-d H:i:s\n" ); //apply the format you want.
如果我错了,请评论......