简体   繁体   English

每个foreach循环两个项目

[英]Two items per foreach loop

Apologies if this has already been asked (I cannot find an answer) but I am using PHP and I am building a slider, but would like two images per slide, not one. 抱歉,如果有人问过这个问题(我找不到答案),但是我正在使用PHP,并且正在构建一个滑块,但是希望每个幻灯片有两个图像,而不是一个。 So, in theory the foreach() needs to include two per each. 因此,从理论上讲, foreach()每个必须包含两个。

An example of the setup is as follows: 设置示例如下:

<?php foreach ($page->images as $image) : ?>
    <img src="<?php echo $image->url; ?>"/> 
<?php endforeach; ?>

I was thinking I could do something like a count... 我以为我可以做点算...

<?php $index = 0; foreach ($page->images as $image) : ?>
    <img src="<?php echo $image->url; ?>"/>
    <?php $index++; ?>
    <?php if ( $index % 2 == 0 && $index !=count($page->images) ) : ?>
    <li></li>
    <?php endif; ?>
<?php endforeach; ?>

But I got a little confused as this would insert something every 2... not include two of whatever the foreach loop is fetching at once. 但是我有点困惑,因为这会每2插入一次...不包括两个foreach循环一次获取的内容。

Hope this makes sense and thanks in advance 希望这有意义并且在此先感谢

Why so complicated? 为什么这么复杂? Use a simple for loop instead: 使用简单的for循环:

<?php for ($i=0; $i<count($page->images)-1; $i+=2) { ?>
    <img src="<?php echo $page->images[$i]->url; ?>"/> 
    <img src="<?php echo $page->images[$i+1]->url; ?>"/> 
<?php } ?>

Or even more elegant, a do/while loop: 甚至更优雅的是,一个do/while循环:

<?php $i=0; do { ?>
    <img src="<?php echo $page->images[$i++]->url; ?>"/> 
    <img src="<?php echo $page->images[$i++]->url; ?>"/> 
<?php } while ($i<count($page->images)) ?>

Compared to using a foreach loop these approaches have another advantage: you do not create copies of all objects. 与使用foreach循环相比,这些方法还有另一个优点:您无需创建所有对象的副本。 This can make a huge difference if those objects are non-trivial. 如果这些对象不平凡,则可能会产生巨大的差异。

Okay, I managed to work this out... hopefully it will help. 好的,我设法解决了这个问题……希望能对您有所帮助。

<div class="each-slide">
<?php $index = 0; foreach ($page->images as $image) : ?>
    <img src="<?php echo $image->url; ?>"/>
    <?php $index++; ?>
    <?php if ( $index % 2 == 0 && $index !=count($page->images) ) : ?>
        </div><div class="each-slide">
    <?php endif; ?>
<?php endforeach; ?>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM