Two foreach loops with same variable names break the order of elements

后端 未结 1 876
梦毁少年i
梦毁少年i 2021-01-23 18:14

Here is my code:

foreach($datawallright[\'adds\'] as &$ad){
    $ad[\'img\'] = get_ad_pic_url($this->em->getReference(\"models\\MmAds\",$ad[\'id\']),\'         


        
相关标签:
1条回答
  • 2021-01-23 18:43

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题