Nested foreach in PHP gives results other than expected

I have trouble repeating twice in 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 code above prints:

code result

And I expect to see something like this (the combo labels on the images do not match, but I think the idea is clear):

expected results

thank you in advance

+5
source share
4 answers

My first instinct does not use loops foreach. I believe that PHP uses some internal pointers, so two loops foreachaffect every other position. Use a regular loop instead.

+9
source

, , foreach outher. 0 . - :

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

,

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

not

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

$commision1 anyware

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

, :

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

- PHP:

": foreach reset ." [: http://www.php.net/manual/en/control-structures.foreach.php]

foreach , .:)

0

All Articles