PHP for循环不递增

时间:2017-03-01 14:40:18

标签: php

我有以下PHP代码:

$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;
}

计数器$ i根本没有增加。 $ i保持在Object { date="2017-03-02 20:00:55.000000", timezone_type=3, timezone="Asia/Kolkata"}

2 个答案:

答案 0 :(得分:1)

根据RiggsFolly的建议,我将代码更新为以下内容:

$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');
}

现在正在运作。唯一的变化是行$json['message'][] = $i->format('d-m-Y');

答案 1 :(得分:-1)

我不确定为什么这是必要的,我很想知道原因。但是如果你将$i转换成一个数组,然后再回到一个对象就行了。

$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);

结果:

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
相关问题