两个具有相同变量名的foreach循环打破了元素的顺序 [英] Two foreach loops with same variable names break the order of elements

查看:88
本文介绍了两个具有相同变量名的foreach循环打破了元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

foreach($datawallright['adds'] as &$ad){
    $ad['img'] = get_ad_pic_url($this->em->getReference("models\MmAds",$ad['id']),'/crop_');
    $ad['description'] = ucfirst(strip_tags(html_entity_decode(mb_strtolower(str_replace(array("___","---"),"",$ad['description']), "UTF-8"))));
    $ad['titleurl'] = title_url($ad['title']);
}

foreach($datawallright['adds'] as $ad){

    $this->load->view("view_wallpage_add",array("ad"=>$ad,"isuserwall"=>$isuserwall));
}

我有两个for循环通过同一数组.在这两个for循环中分配的变量是相同的.奇怪的是,当它遍历第二个for循环时.前n-1个元素是正确的,但出现在最后一个元素之前的元素代替了最后一个元素.我可以在for循环中完成所有操作.我可以更改变量$ ad的名称,然后它可以正常工作,但是我想知道发生了什么.

I have two for loops going through the same array. The variables assigned in this two for loops are the same. The weird thing is when it iterates through the second for loop. The first n-1 element are correct, but in the place of the last element the element that is one before last appeares. I can do it all in one for loop. I can change the name of the variable $ad and then it works fine, but I want to know what happened.

推荐答案

发生的事情是第一个循环通过引用进行迭代,因此,当第二个循环尝试将当前项"分配给$ad时,实际上会更新您的数组内容除了更新$ad.

What happened is that the first loop iterates by reference, so when the second attempts to assign "the current item" to $ad it actually updates your array contents in addition to updating $ad.

最简单的解决方法是在第一个foreach之后立即添加一个unset ($ad),以使PHP从那时起不再将名称$ad视为引用.

The simplest fix is to add an unset ($ad) immediately after the first foreach so that PHP will not consider the name $ad a reference from that point onward.

需要这样做(否则以后会对参考进行隐藏更新)是在PHP中可能使您无法使用的最丑陋的事情之一;就个人而言,我非常虔诚地希望在引用引用后添加unset,即使那是函数中的最后一条语句.

The need to do this (or else suffer from hidden updates to the reference later on) is one of the ugliest things that can bite you in PHP; personally I am very religious about appending an unset after iterating by reference, even if that's the last statement in a function.

这篇关于两个具有相同变量名的foreach循环打破了元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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