可能重复:
当我两次迭代这个数组(通过引用,通过值(时,为什么PHP会覆盖值
我得到了一个数组,如果我打印它,它看起来像:
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循环中的每个子数组时,它看起来像:
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个条目。这对我来说是个谜。有人知道为什么会发生这种事吗?
decze的注释基本上解决了这个问题。我用过:
foreach($products as &$product){
然后在$product中添加了一些条目。替换为:
foreach($products as $key=>$product){
修改$products[$key]解决了问题
感谢=D