滑块动态图像的逻辑循环与PHP

时间:2018-01-24 05:43:20

标签: php twitter-bootstrap codeigniter carousel

我正在使用bootstrap carousel滑块。我试图用PHP数组加载滑块中的动态图像。我在PHP数组中有4个(计数不固定)图像路径。

我的HTML代码如下:

<div class="carousel-inner">
    <div class="item active">
        <a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar2.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar3.jpg" alt=""></a>
    </div>
    <div class="item">
        <a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar2.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar3.jpg" alt=""></a>
    </div>
    <div class="item">
        <a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar2.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar3.jpg" alt=""></a>
    </div>
</div>

我需要一个逻辑来循环数组并在html中加载我的图像。

我的预期HTML就像

<div class="carousel-inner">
    <div class="item active">
        <a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar2.jpg" alt=""></a>
        <a href=""><img src="<?=base_url()?>images/product-details/similar3.jpg" alt=""></a>
    </div>
    <div class="item">
        <a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>    
    </div>
</div>

请帮帮我

2 个答案:

答案 0 :(得分:2)

喜欢这个

<div class="carousel-inner">
    <div class="item active">
        <?php
        $count = 0;
        foreach ($images as $key => $image)
        {
            if ($count == 2)
            {
            ?>
                </div>
                <div class="item">
                <?php
                $count = 0;
            }
            ?>
                <a href=""><img src="<?=base_url()?>images/product-details/<?= $image?>" alt=""></a>
            <?php
            $count += 1;
        }
        ?>
    </div>
</div>

您应该在上面的代码中做什么

  1. $images应该是您的阵列名称
  2. <?=base_url()?>images/product-details/<?= $image?>在此处添加正确的路径
  3. 以上代码会发生什么

    每次<a>标签都在<img>内打印,只要符合if == 2(计数为3),它就会添加新的<div>并将计数设为0 < / p>

答案 1 :(得分:1)

$ count = 1;

 foreach( $images as $img ) 
 {
   if ($count%4 == 1)
  {  
     echo '<div class="item active">';

  }
  echo '<a href=""><img src="<?=base_url()?>images/product-details/similar1.jpg" alt=""></a>';

  if ($count%4 == 0)
  {
          echo "</div>";
  }
   $count++;
 }
  if ($count%4 != 1) echo "</div>";