Search code examples
phploopsfor-loopforeachnested-loops

How to loop foreach inside loop div


i want to create and tabel every showing 3 data from db and continue the next db. exp swiper 1 : (1,2,3) , Swiper 2 : (4,5,6) etc. is it possible to loop a div and have a foreach in it? or any solution. Thanks

<div class="swiper-slide">
<table class="table table-image">
    <tbody>
        <?php
             foreach ($branch as $branchs) : ?>
        <tr>
            <td class="w-25">
                <img
                    src="image/icon/<?= $branchs['imgtitle']; ?>"
                    class="img-fluid img-thumbnail"
                    alt="Sheep">
            </td>
            <td>
                <h4>
                    <b><?= $branchs['title']; ?></b>
                </h4>
                <p class="card-text"><?= $branchs['text']; ?>
                </p>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<div class="swiper-pagination"></div>

Solution

  • Assuming you want a "swipper-slide" and a "swipper-pagination" div every 3 "branchs", this code will loop en the full html and break every 3. You can move HTML code if it is not exactly what you are looking for, but hope that will help.

    <?php $counter = 0; $last = count($branch) - 1; ?>
    <?php foreach ($branch as $branchs): ?>
        <?php if (!($counter % 3)): ?>
            <div class="swiper-slide">
            <table class="table table-image">
            <tbody>
        <?php endif; ?>
        <tr>
            <td class="w-25">
                <img
                    src="image/icon/<?= $branchs['imgtitle']; ?>"
                    class="img-fluid img-thumbnail"
                    alt="Sheep">
            </td>
            <td>
                <h4>
                    <b><?= $branchs['title']; ?></b>
                </h4>
                <p class="card-text"><?= $branchs['text']; ?>
                </p>
            </td>
        </tr>
        <?php $counter ++; ?>
        <?php if (($counter === $last) || !($counter % 3)): ?>
            </tbody>
            </table>
            </div>
            <div class="swiper-pagination"></div>
        <?php endif; ?>
    <?php endforeach; ?>