![Creative The name of the picture]()
php reverse order of time period in foreach
hi i have script gives me list of days date between a week.
i need the reverse the the order.
alredy tried rsort, reverse_array, and much more some how all giving error.
thanks.
script
$date2 = "$lastweek2";
$date1 = "$lastweek1";
$start = new DateTime($date2);
$end = new DateTime($date1);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
echo "<br>";
foreach ($period as $dt) {
echo $dt->format("Y-m-d") . "<br>n";
}
echo is like this
2014-08-09
2014-08-10
2014-08-11
2014-08-12
2014-08-13
2014-08-14
2014-08-15
reversed
2014-08-15
2014-08-14
2014-08-13
2014-08-12
2014-08-11
2014-08-10
2014-08-09
4 Answers
4
Just put the dates in an array and then reverse the order of the array using array_reverse()
array_reverse()
$dates = array();
foreach ($period as $dt) {
$dates = $dt->format("Y-m-d");
}
$dates = array_reverse($dates);
echo implode("<br>n", $dates);
2014-08-16 - today 2014-08-16 - 0 week ago 2014-08-09 - 1 week ago
$period = array_reverse(iterator_to_array($period));
Using a negative one day interval and the difference of days between the two dates you can accomplish the same thing without needing to use array_reverse(iterator_to_array()) or build another array.
array_reverse(iterator_to_array())
Example: https://3v4l.org/B3nNk
$start = new DateTime('2014-08-15');
$end = new DateTime('2014-08-09');
$diff = $end->diff($start);
$interval = DateInterval::createFromDateString('-1 day');
$period = new DatePeriod($start, $interval, $diff->days);
foreach ($period as $date) {
echo $date->format('Y-m-d') . PHP_EOL;
}
Result:
2014-08-15
2014-08-14
2014-08-13
2014-08-12
2014-08-11
2014-08-10
2014-08-09
In this way it tells DatePeriod to subtract 1 day, for the number of days returned from the diff, instead of adding up until the end date.
DatePeriod
$date1 = "2014-08-15";
$date2 = "2014-08-09";
$start = new DateTime($date2);
$end = new DateTime($date1);
$i = DateInterval::createFromDateString('1 day');
while ($end >= $start) {
echo $end->format("Y-m-d") . "<br>n";
$end = $end->sub($i);
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What's your question? What error do you get? Show the code giving you an error.
– John Conde
Aug 15 '14 at 20:28