I have the following PHP code:
$todaysdate = date_create();
for ($i = date_sub(date_create(),date_interval_create_from_date_string("1 month")); $i <= $todaysdate; $i = date_add($i,date_interval_create_from_date_string("1 day"))) {
$json['message'][] = $i;
}
The counter $i doesnot increment at all. $i remains at Object { date="2017-03-02 20:00:55.000000", timezone_type=3, timezone="Asia/Kolkata"}
As suggested by RiggsFolly, I updated the code to the following:
$todaysdate = date_create();
for ($i = date_sub(date_create(),date_interval_create_from_date_string("1 month")); $i <= $todaysdate; $i = date_add($i,date_interval_create_from_date_string("+1 day"))) {
$json['message'][] = $i->format('d-m-Y');
}
It's now working. The only change was the line $json['message'][] = $i->format('d-m-Y');
I am not sure why this is necessary, and I would love to know the reason. But if you cast $i
into an array and then back to an object it works.
$todaysdate = date_create();
for ($i = date_sub(date_create(),date_interval_create_from_date_string("1 month")); $i <= $todaysdate; $i = date_add($i,date_interval_create_from_date_string("1 day"))) {
$json[] = (object)(array)$i;
}
print_r($json);
Result:
Array
(
[0] => stdClass Object
(
[date] => 2017-02-01 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[1] => stdClass Object
(
[date] => 2017-02-02 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[2] => stdClass Object
(
[date] => 2017-02-03 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[3] => stdClass Object
(
[date] => 2017-02-04 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[4] => stdClass Object
(
[date] => 2017-02-05 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[5] => stdClass Object
(
[date] => 2017-02-06 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
[6] => stdClass Object
(
[date] => 2017-02-07 15:34:21.500729
[timezone_type] => 3
[timezone] => UTC
)
.... etc