2012-10-15 108 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