How to divide items into each X items

0

I am using PHP to receive the data from the server but I want to make every 7 items a div closed and open a new one however I can not.

Example:

<div class='grupo'>
    <item>
    <item>
    <item>
    <item>
    <item>
    <item>
    <item>
</div>
<div class='grupo'>
.....
</div>
    
asked by anonymous 25.02.2018 / 04:06

1 answer

1

Just use a foreach , divide the count value by 7, and capture the rest of the division. If it is 0, close the tag.

You can capture this value using $count % 7 === 0 .

Example:

<?php

$arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];

/* Imprime a aberta da tag */
echo '<div class="grupo" style="background:red;margin-bottom:10px">';

$count = 1;

foreach($arr as $value) {

    echo "<p>{$value}</p>";

    /** 
     * Verifica se o número é divisível por 7 e se 
     * a contagem é menor ou igual ao número 
     * de elementos do array
     */
    if ( $count++ % 7 === 0 && count($arr) >= $count ) {
        echo '</div><div class="grupo" style="background:red;margin-bottom:10px">';
    }
}

/* Fecha a tag */
echo '</div>';
    
25.02.2018 / 04:23