Packy Packy - 5 months ago 39
PHP Question

php foreach wrap every 2 divs

I need to wrap every 2 divs with another div for a project (a row) so it will look like:

<div class="row">
<div> Item </div>
<div> Item </div>
</div>
<div class="row">
<div> Item </div>
<div> Item </div>
</div>


I have tried a few solutions but they dont work since the items coming in are odd (9 items). Here is what I had:

<?php
$count = 0;
foreach ($contents as $content)
{
//var_dump($content);
$books = $content["tags"];
$book_image = $content['content_image'];
$book_desc = $content['content_social_description'];

++$count;

if($count == 1)
{
echo "<div class='et_pb_row'>";
}

foreach ($books as $book)
{
$book_name = $book['tag_name'];
$book_name_trim = str_replace(' ', '-', $book_name);
?>
<!-- Inside the Book Loop -->
<div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
<h2><?php echo $book_name; ?></h2>
<p><?php echo $book_desc; ?></p>
<?php echo $count; ?>
</div>

<?php

}

if ($count == 2)
{
echo "</div>";
$count = 0;
}
}
?>


This works except the second to last row has 3 items even though it dispays the "count" as 2 when I echo it out so it should reset but doesnt. So its:

<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
<div> Item </div> "Count 2"
</div>
<div class="row">
<div> Item </div> "Count 1"
<div> Item </div> "Count 2"
</div>

Answer

You should open and close your <rows/> in the books loop, and add a late check for odd books:

<?php 
$count = 0;
foreach ($contents as $content) 
{
    //var_dump($content);
    $books      = $content["tags"];
    $book_image = $content['content_image'];
    $book_desc  = $content['content_social_description'];


    foreach ($books as $book) 
    {
        ++$count;
        if($count == 1)
        {  
            echo "<div class='et_pb_row'>";
        }
        $book_name      = $book['tag_name'];
        $book_name_trim = str_replace(' ', '-', $book_name);
        ?>
        <!-- Inside the Book Loop -->
        <div class='et_pb_column et_pb_column_1_2 books' style="background: url('https://s3-us-west-2.amazonaws.com/crowdhubproverbs31/<?php echo $book_image ;?>');">
            <h2><?php echo $book_name; ?></h2>
            <p><?php echo $book_desc; ?></p>
            <?php echo $count; ?>
        </div>

        <?php
        if ($count == 2)
        {
            echo "</div>";
            $count = 0;
        }


    }
}

if ($count > 0)
{
    echo "</div>";
}
?>

Doing so, your $count variable will be incremented only when foreach($books AS $book) loop is run (thus you have at least one book to print)

Comments