如何控制这个foreach循环

时间:2012-04-19 13:14:56

标签: php

我使用这个foreach来构建youtube视频库但我想为每一行显示3个视频..那么如何指定循环3次然后移动到下一行并循环3次... 我不需要在一行中构建所有循环.. 谢谢你的帮助

table id="tblThumbsLayout" cellpadding="0" cellspacing="6">

<tr>

   <?php  foreach ($vcats as $vcat) { ?>

<td class="tdImg">
    <div>

      <?php  echo '<iframe class="youtube-player" type="text/html" width="  200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
        <div class="text"><?php echo  '<b>'.  $vcat['Video']['title'].'</b>' ; ?></div>
    </div>
</td>
<?php  } ?>
</tr>
</table>

4 个答案:

答案 0 :(得分:1)

试试这个:

   <?php  
        $i = 1; 
        foreach ($vcats as $vcat) { 
        if($i%3 == 0){
           echo "</tr><tr>";
        }

   ?>

    <td class="tdImg">
        <div>

          <?php  echo '<iframe class="youtube-player" type="text/html" width="  200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
            <div class="text"><?php echo  '<b>'.  $vcat['Video']['title'].'</b>' ; ?></div>
        </div>
    </td>

    <?php $i++; } ?>

答案 1 :(得分:1)

我会在每个项目和样式表中为div id添加div id = video #video use display:inline;

然后将div的宽度设置为每行3个。

这样你就不用太担心循环了。

答案 2 :(得分:0)

保持循环迭代的计数。然后使用模数运算符,检查此迭代除以3的余数是否为0.如果是,则添加一个断行或新表行以移动到下一行。

像这样:

<table id="tblThumbsLayout" cellpadding="0" cellspacing="6">

<tr>

   <?php  
       $counter = 1;
       foreach ($vcats as $vcat) {
   ?>

<td class="tdImg">
    <div>

      <?php  echo '<iframe class="youtube-player" type="text/html" width="  200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
        <div class="text"><?php echo  '<b>'.  $vcat['Video']['title'].'</b>' ; ?></div>
    </div>
</td>
<?php
       if($counter % 3 == 0){
          echo '<br/>';
        }
       ++$counter;
    }
?>
</tr>
</table>

答案 3 :(得分:0)

<table id="tblThumbsLayout" cellpadding="0" cellspacing="6">

<tr>
   <?php $counter = 1; $last = count($vcats)-1; ?>
   <?php  foreach ($vcats as $vcat) { ?>

<td class="tdImg">
    <div>

      <?php  echo '<iframe class="youtube-player" type="text/html" width="  200 " height=" 100 " src="http://www.youtube.com/embed/' . $vcat['Video']['link'] . '"></iframe>' ;?>
        <div class="text"><?php echo  '<b>'.  $vcat['Video']['title'].'</b>' ; ?></div>
    </div>
    <?php if($counter%3==0 && $counter != $last): ?>
        <br>
    <?php $counter++;  ?>
    <?php endif; ?>
</td>
<?php  } ?>
</tr>
</table>
相关问题