如何按范围计算foreach循环 [英] How to count foreach loop by range

查看:40
本文介绍了如何按范围计算foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将轮播幻灯片图片幻灯片每张幻灯片放4张图片.我希望每张幻灯片显示四张图像,然后下一张幻灯片将显示另外四张图像.我希望我解释得很好.

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
    $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
  }
?>

关键是要使用$k,只要它可以被功能$k % $numImagesPerSlide == 0整除为4(4、8、12、16,...),就可以打印所需的代码. 我想您将需要一个额外的代码,例如

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
}

这篇关于如何按范围计算foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆