开发者

Nested foreach in PHP produces different results than I expect

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 forea开发者_如何学Cch ($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:

Nested foreach in PHP produces different results than I expect

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

Nested foreach in PHP produces different results than I expect

Thanks in advance


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.


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
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜