2012-10-15 107 views
0

可能重复:
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被添加到$ all日期它会像我期望的那样为$ 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

你在另一个问题中没有添加你的函数函数而不是创建一个新的函数? 。 – Baba

+0

因为它基本上变成了一个不同的问题。问题的原始标题是询问不属于这个问题的foreach。原来的问题有一些回声,混淆了我想要做的事情。此外,如果有人遇到这个问题,未来这个问题(这个答案,谢谢AndreKR)更有可能解决他们的问题。 – Casey

回答

1

$start$end是对象,它们总是通过引用分配的结果。您需要创建新的独特对象。有关如何执行此操作,请参见How do I deep copy a DateTime object?

+0

非常感谢。我本来可以在该代码上出演一年,我不会想到他们是通过引用分配的。 – Casey