对于循环不向上递增日期

时间:2014-01-24 05:59:18

标签: php arrays

我有以下代码向数组添加4个日期,但数组中每个值的日期保持不变。 它只给了我2014/01/24而不是2014/01 / 24,2014 / 01 / 31,2014 / 02 / 07,2014 / 02/14的4个值

由于

        $myArray = array(); 

        // Number of days
        $days = get_post_meta($post_id, 'wpcf-inc_recur_freq', true);

         // cycle from 1st week's due date to the end of payment cycle
        for($i = 1; $i <= 4; $i++) {

             $myArray[] = date($mysqldate, strtotime("+" . $days . " days"));

        }

4 个答案:

答案 0 :(得分:2)

是的,它会为您提供同一日期的四份副本,因为您只是每次都会在当前日期添加固定天数。

我认为您可能希望将for循环更改为:

for($i = 0; $i < 4; $i++) {
    $myArray[] = date($mysqldate, strtotime("+" . ($days * $i) . " days"));
}

请注意,我已经将循环更改为运行0..3而不是1..4,假设您想要的第一个日期是今天。如果您真正想要的第一个日期是今天$days天,请恢复使用1..4


您可以在以下PHP代码中看到这一点:

date_default_timezone_set("EST");
$myArray = array();
$days = 7;
for($i = 0; $i < 4; $i++) {
    $myArray[] = date("Y-m-d", strtotime("+" . ($days * $i) . " days"));
}
var_dump($myArray);

输出(使用one of the online PHP executors):

array(4) {
    [0]=> string(10) "2014-01-24"
    [1]=> string(10) "2014-01-31"
    [2]=> string(10) "2014-02-07"
    [3]=> string(10) "2014-02-14"
}

但是,可能是您的实际$days变量设置为零(您似乎认为它将设置为7)。 $days值为零会导致所有日期都是今天,即使上面的更正代码也是如此,所以我会检查它。将值设置为零的一个可能性是您正在查找的键中下划线和连字符的不寻常混合:

wpcf-inc_recur_freq
    ^   ^     ^
    |   |     |
    |   +-----+------- underscore
    +----------------- hyphen

我怀疑你在输入第一个_字符时应该没有按下SHIFT键那么难: - )

答案 1 :(得分:1)

你没有在循环中增加$ days,所以每次循环执行时它都会给出相同的值。

答案 2 :(得分:0)

你的循环中没有增加$ days。

$mysqldate = date('Y-m-d');

// Number of days
$days = get_post_meta($post_id, 'wpcf-inc_recur_freq', true);

// cycle from 1st week's due date to the end of payment cycle
for($i = 1; $i <= 4; $i++) {
    $myArray[] = date($mysqldate, strtotime("+" . $i*$days . " days"));
}
var_dump($myArray);

答案 3 :(得分:0)

试试这个。

         $mysqldate = date('Y-m-d');

        // Number of days
        $days = get_post_meta($post_id, 'wpcf-inc_recur_freq', true);

        // cycle from 1st week's due date to the end of payment cycle
        for($i = 1; $i <= 4; $i++) {
            $myArray[$i] = date($mysqldate, strtotime("+" . $i*$days . " days"));
        }
        var_dump($myArray);
相关问题