Maurizio
Maurizio

Reputation: 89

While-loop: group two result on one div

I would add each two result one div class

<?php while ($fetch = $db->fetch($query)) { ?>
   <?php echo $fetch['title']; ?>
<?php } ?>

Output should be like this

<div class="one">
    <div class="two">
       <article>Title</article>
       <article>Title</article>
    </div>
</div>
<div class="one">
    <div class="two">
       <article>Title</article>
       <article>Title</article>
    </div>
</div>>

Upvotes: 0

Views: 856

Answers (2)

Daniel
Daniel

Reputation: 475

<?php
$i=0;
while ($fetch = $db->fetch($query)) { ?>

    <?php if ($i%2==0) { ?>
    <div class="one">
        <div class="two">
    <?php } ?> 

       <article><?php echo $fetch['title']; ?></article>

    <?php if ($i++%2==1) { ?>
        </div>
    </div>
    <?php } ?> 

<?php } ?>

//Also is a good idea to verify if the <div> tags are closed

<?php if ($i%2==1) { ?>
        </div>
    </div>
<?php } ?>

Upvotes: 1

BMN
BMN

Reputation: 8508

$count = 0;
while ($fetch = $db->fetch($query))
{
    if ($count == 0)
        echo '<div class="one"><div class="two">';
    if ($count < 2)
        echo '<article>'.$fetch['title'].'</article>';
    if ($count == 2)
    {
        echo '</div></div>';
        $count = 0;
    }
    $count++;
}

Upvotes: 0

Related Questions