简体   繁体   中英

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. So, in theory the foreach() needs to include two per each.

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.

Hope this makes sense and thanks in advance

Why so complicated? Use a simple for loop instead:

<?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:

<?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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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