How to divide items with each X items

Asked

Viewed 66 times

0

I’m using PHP to receive the data from the server but I want to make every 7 items the div is closed and open a new but I’m not getting.

Example:

<div class='grupo'>
    <item>
    <item>
    <item>
    <item>
    <item>
    <item>
    <item>
</div>
<div class='grupo'>
.....
</div>

1 answer

1


Just use a foreach, divide the count value by 7 and capture the rest of the division. If 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>';
  • Thank you very much, it helped a lot I was on the right track but otherwise :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.