2012-02-29 18 views
2

我試圖直接更新數組的某些值。這是完美的工作。我正在使用以下方法:&Array() - 在更新數組之後加上「&」前綴的最後一行

foreach($items as &$item) { 
    if($criteria == 'correct') { 
     // update array 
     $item['update_me'] = 'updated'; 
    } 
} 

因此,我現在有一個名爲$ items的更新數組。

但是,我遇到的問題是,當此數組輸出到屏幕(通過另一個foreach循環)時,數組的最後一行丟失。

如果我通過var_dump($ items)打印整個數組;方法,我注意到每一行都以Array(9)作爲前綴。然而,最後一行以前綴&數組(9)爲前綴 - 注意主要的&符號。我相信這很重要!但我不確定它的含義。爲什麼它只應用於數組中的最後一行?我該如何擺脫它?

從評論:

array(6) { 
    [0]=> array(9) { 
     ["item_id"]=> string(4) "1" 
     ["item_description"]=> string(9) "blah blah" 
     ["quantity"]=> string(1) "4" 
     ["unit_cost"]=> string(4) "5.00" 
     ["subtotal"]=> string(4) "20.00" 
    } 
    [1]=> &array(9) { 
     ["item_id"]=> string(4) "2" 
     ["item_description"]=> string(9) "blah blah" 
     ["quantity"]=> string(1) "1" 
     ["unit_cost"]=> string(4) "5.99" 
     ["subtotal"]=> string(4) "5.99" 
    } 
} 
+0

向我們展示所有相關的代碼。向我們展示相關輸出。告訴我們你使用的是什麼語言。 – Marcin 2012-02-29 11:45:53

+0

請給我一個測試用品。 – 2012-02-29 11:49:50

+0

現在應該有希望修復。但這裏是輸出以防任何人有興趣參考:'array(6) {[0] => array(9) \t {[「item_id」] => string(4)「1」 \t [ ITEM_DESCRIPTION 「] =>串(9) 」等等等等「 \t [」 量 「] =>串(1) 」4「 \t [」 UNIT_COST 「] =>串(4) 」5.00「 \t [」 小計「] =>串(4) 」20.00「 \t} [1] =>&陣列(9) \t {[」 ITEM_ID 「] =>串(4) 」2「 \t [」 ITEM_DESCRIPTION「] => string(9)「blah blah」 \t [「quantity」] => string(1)「1」 \t [ 「UNIT_COST」] =>串(4) 「5.99」 \t [ 「小計」] =>串(4) 「5.99」 \t} }' – user1100149 2012-02-29 12:10:29

回答

1

我認爲這不是最好的方法來做到這一點。我建議這樣做:

foreach(array_keys($items) as $itemkey) { 
    if($criteria == 'correct') { 
     // update array 
     $items[$itemkey]['update_me'] = 'updated'; 
    } 
} 
+0

這看起來效果更好!需要做一些測試,以確保它保持不變,但非常好。謝謝。 – user1100149 2012-02-29 12:09:18

5

我不知道這是否是這裏的情況,而是通過引用被稱爲foreach循環導致這些類型的問題,如果引用不是後未設定循環(有關於它的警告in the manual)。在foreach更新完成後立即嘗試添加unset($item);,看看它是否能解決問題。

+0

這很有趣。下面的解決方案似乎已經奏效,但我也可能因爲好奇而嘗試。 – user1100149 2012-02-29 12:09:55

11

您必須在循環後取消設置$ item。正確的代碼:在後續代碼var_dump結果

foreach($items as &$item) { 
    if($criteria == 'correct') { 
     // update array 
     $item['update_me'] = 'updated'; 
    } 
} 
unset($item); 

&標誌指定這是參考。您可以使用xdebug_zval_dump()函數檢查它:

xdebug_zval_dump($item) 

您會看到is_ref = true。在PHP中,這意味着還有另一個變量指向同一個zval容器(什麼是zval?請參見http://php.net/manual/en/internals2.variables.intro.php)。 如果您在循環中使用&,則必須始終在循環後取消設置參考,以避免難以檢測到的錯誤。