How to count foreach loop by range

2020-04-30 03:14发布

I'm trying to make the carousel slide image slide by 4 images per slide. I want each slide to display four images, and then the next slide will display another four images. I hope I have explained well.

<?php
$i = 0;
foreach ($photos as $photo) {
    if ($i == 0) {
        ?>
        <div class="carousel-item active">
            <ul class="thumbnails">
                <li class="span3">
                    <div class="thumbnail">
                        <i class="tag"></i>
                        <a href="#">
                            <img src="<?php echo $photo->image_path(); ?>" width="125" height="125" class="img-thumbnail" alt="buy more"/>
                        </a>
                    </div>
                </li>
            </ul>
        </div>
        <?php
        $i++;
    } else {
        if ($i != 0) {
            ?>
            <div class="carousel-item">
                <ul class="thumbnails">
                    <li class="span3">
                        <div class="thumbnail">
                            <i class="tag"></i>
                            <a href="#">
                                <img src="<?php echo $photo->image_path(); ?>" width="125" height="125" class="img-thumbnail" alt="buy more"/>
                            </a>
                        </div>
                    </li>
                </ul>
            </div>
            <?php
        }
        $i++;
    }
}
?>

标签: php html loops
1条回答
Fickle 薄情
2楼-- · 2020-04-30 03:51

I believe that will do the trick:

<?php
    $numImagesPerSlide = 4;
    foreach($photos as $k => $photo){
?>
    <div class="carousel-item <?php echo ($k % $numImagesPerSlide == 0) ? 'active': '';?>">
        <ul class="thumbnails">
            <li class="span3">
                <div class="thumbnail">
                <i class="tag"></i>
                <a href="#"><img src="<?php echo $photo->image_path(); ?>" width="125" height="125" class="img-thumbnail" alt="buy more"/></a>
                </div>
            </li>
        </ul>
    </div>
<?php
  }
?>

The point is to use $k, whenever it is divisible by 4 (4, 8, 12, 16, ...), with the function $k % $numImagesPerSlide == 0 then you print the code you need. I guess you will need an extra code, like

if ($k % $numImagesPerSlide == 0) {
    //print the header of the carrousel
}
查看更多
登录 后发表回答