可能重复:
How do I deep copy a DateTime object?
Error in adding to 2d array or looping through 2d array
所以我的代码是:
while ($end <= $to){
$currentDates = array("from" => $start, "to"=>$end);
$allDates[] = $currentDates;
echo '<br>', var_dump($allDates);
unset($currentDates);
$start->add($intervalObj);
$end->add($intervalObj);
}
但每次将$ currentDates添加到$ allDates时,它会像我期望的那样为$ allDates添加一个位置,但它也会用$ currentDates的当前值覆盖所有先前的数组位置。
这是循环中var_dump的结果
array(1) { [0]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-10 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-11 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } }
array(2) { [0]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-11 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-12 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } [1]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-11 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-12 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } }
array(3) { [0]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-12 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-13 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } [1]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-12 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-13 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } [2]=> array(2) { ["from"]=> object(DateTime)#6 (3) { ["date"]=> string(19) "2012-10-12 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } ["to"]=> object(DateTime)#7 (3) { ["date"]=> string(19) "2012-10-13 00:00:00" ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" } } }
答案 0 :(得分:1)
$start
和$end
是对象,始终通过引用分配。您需要创建新的,不同的对象。有关如何执行此操作,请参阅How do I deep copy a DateTime object?。