2011-10-12 65 views
0

可能重複:
Why does PHP overwrite values when I iterate through this array twice (by reference, by value)PHP數組被通過的foreach搞砸了

我得到了它,如果我print_r的它看起來像一個數組:

Array 
(
    [0] => Array 
     (
      [0] => 13 
      [product_id] => 13 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 0 
      [vat included] => 0 
      [price] => 3 
      [unit] => test3 
      [product number] => 3 
     ) 
    [1] => Array 
     (
      [0] => 12 
      [product_id] => 12 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 1 
      [vat included] => 0 
      [price] => 2 
      [unit] => test2 
      [product number] => 2 
     ) 
    [2] => Array 
     (
      [0] => 11 
      [product_id] => 11 
      [1] => 1 
      [account_id] => 1 
      [vat type] => 2 
      [vat included] => 0 
      [price] => 1 
      [unit] => test1 
      [product number] => 1 
     ) 
) 

現在,當我使用foreach循環它會發生一些奇怪的事情。當我print_r在foreach循環中的每個子陣列它看起來像:

Array 
(
    [0] => 13 
    [product_id] => 13 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 0 
    [vat included] => 0 
    [price] => 3 
    [unit] => test3 
    [product number] => 3 
) 
Array 
(
    [0] => 12 
    [product_id] => 12 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 1 
    [vat included] => 0 
    [price] => 2 
    [unit] => test2 
    [product number] => 2 
) 
Array 
(
    [0] => 12 
    [product_id] => 12 
    [1] => 1 
    [account_id] => 1 
    [vat type] => 1 
    [vat included] => 0 
    [price] => 2 
    [unit] => test2 
    [product number] => 2 
) 

請注意第3條目。對我來說這是一個神祕的東西。任何人都知道這是爲什麼發生?

+0

您可以添加用於生成第二列表,請您的foreach代碼? –

+0

你能告訴我們你的foreach代碼嗎? –

+1

我的錢說你正在重用一個被引用的變量('foreach($ array as&$ foo)')... – deceze

回答

2

'deceze'的評論幾乎解決了這個問題。 我使用過:

foreach($products as &$product){ 

並將一些條目添加到$ product中。 更換與:

foreach($products as $key=>$product){ 

和修改$產品[$關鍵]解決了這個問題

感謝= d

+1

或者你可以簡單地在循環之後'取消設置($ product)',無論如何你應該這樣做。 – deceze