在PHP中嵌套的foreach会产生与我预期不同的结果 [英] Nested foreach in PHP produces different results than I expect

查看:84
本文介绍了在PHP中嵌套的foreach会产生与我预期不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一数组上迭代两次时遇到问题:

I'm having problems to iterate twice on the same array:

<? $indice=0 ?>
<?php foreach ($comisiones as $comision1):?>  
  <tr>  
    <td><?php echo ++$indice ?></td>  
    <td><?php echo tag('select',array('name'=>'comision_'.$indice),true)?>  
          <?php foreach ($comisiones as $comision2):?>  
            <option value="<?php echo $comision2->getId()?>">
               <?php echo $comision2->getNombre()." - ".$comision2->getDescripcion()?> 
            </option>
          <?php endforeach?> 
        </select>
    </td>
  </tr>
<?php endforeach?>  

上面的代码打印:

我希望看到这样的图像(图像中的连击标签并不相同,但我认为思路很清楚):

And I'm expecting to see something like this (labels of the combos in the images are not the same, but I think the idea is clear):

预先感谢

推荐答案

我的第一个建议是不要使用foreach循环.我相信PHP正在使用一些内部指针,因此两个foreach循环会影响彼此的位置.而是使用普通的for循环.

My first instict is don't use foreach loops. I believe that PHP is using some internal pointers so the two foreach loops affect each other's position. Instead use a normal for loop.

这篇关于在PHP中嵌套的foreach会产生与我预期不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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