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

查看:107
本文介绍了为什么php迭代引用返回重复的最后一条记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只花了2个小时来寻找一个显然来自foreach迭代的错误并带有& value。我有一个multidimentional数组,当运行时:

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返回一个具有相同元素数的数组,但是有一个DUPLICATE最后记录。有什么我不明白这个结构吗?

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 这里和你绊倒了一个被报告为bug一千次但是引用的正确行为的行为,这就是手册建议

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循环之后,值和最后一个数组元素仍然存在。建议通过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天全站免登陆