有条件的Foreach声明

时间:2014-01-19 19:55:17

标签: php opencart

我正在尝试在OpenCart中使用twitter bootstrap carousel。我只希望第一个横幅让div类“活跃”。我该怎么做呢?

<div id="homepage" class="carousel slide">
        <div class="carousel-inner">

            <?php foreach ($banners as $banner) { ?>
              <div class="item active">

              <?php if ($banner['link']) { ?>
              <a href="<?php echo $banner['link']; ?>"><img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" /></a>
               </div>
              <?php } else { ?>
              <img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" />
              </div>
              <?php } ?>
              <?php } ?>


        </div>

提前致谢

2 个答案:

答案 0 :(得分:1)

例如,使用其他变量$ flag

<div id="homepage" class="carousel slide">
    <div class="carousel-inner">

        <?php 
          $flag = 0;
          foreach ($banners as $banner) { ?>
          <div class="item <?php echo ($flag==0?"active":"");?>">

          <?php if ($banner['link']) { ?>
          <a href="<?php echo $banner['link']; ?>"><img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" /></a>
           </div>
          <?php } else { ?>
          <img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" />
          </div>
          <?php } ?>
          <?php 
          $flag=1; 
          } ?>


    </div>

答案 1 :(得分:0)

您也可以使用数组的键,而不是选择第一个或第二个等...

<div id="homepage" class="carousel slide">
    <div class="carousel-inner">

    <?php 
      $flag = 0;
      foreach ($banners as $key => $banner) { ?>
      <div class="item <?php echo ($key == 0?"active":"");?>">

      <?php if ($banner['link']) { ?>
      <a href="<?php echo $banner['link']; ?>"><img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" /></a>
       </div>
      <?php } else { ?>
      <img src="<?php echo $banner['image']; ?>" alt="<?php echo $banner['title']; ?>" />
      </div>
      <?php } ?>
      <?php 
      $flag=1; 
      } ?>


</div>