Nested foreach in PHP produces different results than I expect

混江龙づ霸主 提交于 2020-01-03 12:24:03

问题


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?>  

The above code prints:

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):

Thanks in advance


回答1:


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.




回答2:


Based on your code it seems like you don't actually want a foreach loop in the outher loop. Just do a regular for loop from 0 to the size of the array. Something like this:

for ($i = 0; $i < count($comisiones); ++$i) {
    // Do what you want
}



回答3:


I belive thet the second loop should looks like or its related to

<?php foreach ($comision1 as $comision2): ?>

not

<?php foreach ($comisiones as $comision2): ?>  

otherwise you are not using $commision1 from first loop anyware

<?php foreach ($comisiones as $comision1): ?>  



回答4:


Use normal for loops with two indexes, like this:

$len = count($comisiones);
for($i = 0; $i < $len; ++$i)
   for($j = 0; $j < $len; ++$j)

As stated clearly on PHP website:

"Note: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array." [source: http://www.php.net/manual/en/control-structures.foreach.php ]

Therefor your inner foreach loop resets every time the array pointer, that's why you are getting out only a terrible mess. :)



来源:https://stackoverflow.com/questions/2533249/nested-foreach-in-php-produces-different-results-than-i-expect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!