为什么通过引用的php迭代返回重复的最后一条记录? [英] Why php iteration by reference returns a duplicate last record?

查看:23
本文介绍了为什么通过引用的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.

推荐答案

我猜你在这里重用 &$ite​​m 而且你是偶然发现已被报告为错误一千次但引用的正确行为的行为,这就是 手动建议:

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

这篇关于为什么通过引用的php迭代返回重复的最后一条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆