php foreach wrap every 2 divs

后端 未结 2 419
梦毁少年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 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 '';
          foreach($row as $book) {
             //Display the book !
          }
       echo '';
    }
    

提交回复
热议问题