php数组被foreach搞砸了

时间:2011-10-12 11:53:41

标签: php arrays multidimensional-array

  

可能重复:
  Why does PHP overwrite values when I iterate through this array twice (by reference, by value)

我有一个数组,如果我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循环时,会发生奇怪的事情。当我在foreach循环中print_r每个子数组时,它看起来像:

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个条目。这对我来说是一个神秘的东西。谁知道为什么会这样?

1 个答案:

答案 0 :(得分:2)

foreach($products as &$product){

并在$ product中添加了一些条目。 用以下代替:

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

并修改$ products [$ key]解决了问题

谢谢= D