添加到2d数组或循环通过2d数组时出错

时间:2012-10-15 16:39:16

标签: php arrays foreach

我在此代码中遇到问题:

while ($end <= $to){
        $currentDates = array("from" => $start, "to"=>$end);
        $allDates[] = $currentDates;
        echo 'from: ', $currentDates["from"]->format("m-d-y"),'<br>';
        unset($currentDates);
        $start->add($intervalObj);
        $end->add($intervalObj);
    }

var_dump($allDates);

循环中的回显显示正确的值,但vardump显示要在数组的所有位置添加到数组的最后日期

1 个答案:

答案 0 :(得分:1)

我认为你不需要2个循环......

错误来自你的循环

while ($end <= $to){
                ^-------  This was never used

另见

$currentDates = array("from" => $start, "to"=>$end);
         Not in the Condition  --^              ^---- To means something else 

你可以像

一样简单
$start = new DateTime("2012-4-12");
$end = new DateTime("2012-12-12");
$dv = new DateInterval('P24D'); // Every 24 days

echo "<pre>";
while ( $start <= $end ) {
    echo "From ", $start->format('Y-m-d');
    $start->add($dv);
    echo " To ", $start->format('Y-m-d'), PHP_EOL;
}

输出

From 2012-04-12 To 2012-05-06
From 2012-05-06 To 2012-05-30
From 2012-05-30 To 2012-06-23
From 2012-06-23 To 2012-07-17
From 2012-07-17 To 2012-08-10
From 2012-08-10 To 2012-09-03
From 2012-09-03 To 2012-09-27
From 2012-09-27 To 2012-10-21
From 2012-10-21 To 2012-11-14
From 2012-11-14 To 2012-12-08
From 2012-12-08 To 2013-01-01