为什么通过引用的php迭代返回重复的最后一条记录?
我刚刚花了 2 个小时寻找一个错误,该错误显然来自具有 &value 的 foreach 迭代.我有一个多维数组,运行时:
I just spent 2 hours hunting a bug which apparently comes from a foreach iteration with &value. I have a multidimentional array and when a ran this:
foreach($arrayOfJsonMods as &$item){
//TODO memcached votes
}
并且 PHP 返回了一个具有相同元素计数的数组,但最后一条记录是重复的.这个结构有什么我不明白的地方吗?
and PHP returned an array with the same element count, BUT with a DUPLICATE last record. Is there something i don't understand about this structure?
我在另一台机器上运行代码,结果是一样的.
I ran the code on a different machine, and the result was the same.
推荐答案
我猜你在这里重用 &$item
而且你是偶然发现已被报告为错误一千次但引用的正确行为的行为,这就是 手动建议:
I'll guess that you're reusing &$item
here and that you're stumbling across a behavior which has been reported as bug a thousand times but is the correct behavior of references, which is why the manual advises:
即使在 foreach 循环之后,对 $value 和最后一个数组元素的引用仍然存在.建议通过 unset() 销毁.
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
foreach($arrayOfJsonMods as &$item)
{
//TODO memcached votes
}
unset($item);
参见https://bugs.php.net/bug.php?id=29992
相关文章