php foreach wrap every 2 divs

后端 未结 2 418
梦毁少年i
梦毁少年i 2021-01-27 11:10

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

Item
相关标签:
2条回答
  • 2021-01-27 11:58

    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)

    0 讨论(0)
  • 2021-01-27 12:03

    You can take advantage of array_chunk :

    //First make a generator to get all books
    function allBooks($contents) {
        foreach($contents as $content) {    
            foreach($content['tags'] as $book) {
                yield $book; //Here you can yield whatever you want !
            }
        }
    }
    
    //Then create rows
    $itemPerRow = 2;
    $rows = array_chunk(iterator_to_array(allBooks($contents)), $itemPerRow, true);
    
    //Display all 
    foreach($rows as $row) {
       echo '<row>';
          foreach($row as $book) {
             //Display the book !
          }
       echo '</row>';
    }
    
    0 讨论(0)
提交回复
热议问题