2017-09-03 3 views
0

J'essaie de comprendre comment écrire une boucle qui va envelopper chaque groupe de 3 éléments. Cependant, pour la dernière itération, il doit envelopper tout ce qui reste (que ce soit un, deux ou trois éléments)PHP: envelopper chaque groupe de 3 éléments

Donc, fondamentalement, ce genre de modèle:

div 
do stuff 
do stuff 
do stuff 
end-div 
div 
do stuff 
do stuff 
do stuff 
end-div 
div 
do stuff 
do stuff 
do stuff 
end-div 
div 
do stuff 
end-div 

Voici où je suis à ce jour :

<?php 

    $counter = 0; 

    for ($i = 1; $i <= 10; $i++) { 

    if (($counter + 1) % 3 == 0) { 
     echo 'div <br />'; 
    } 
    echo 'do stuff <br />'; 
    if (($counter + 1) % 3 == 0) { 
     echo 'end-div <br />'; 
    } 

    $counter ++; 
    } 

?> 

Cela me donne ce qui suit:

do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 
do stuff 
div 
do stuff 
end-div 
do stuff 

quelqu'un peut voir où je vais mal?

Répondre

0

En d'autres termes, vous devez écrire div avant chaque groupe de trois éléments et end-div après chaque groupe de trois éléments:

// $counter always tells the number of processed items 
$counter = 0; 

for ($i = 1; $i <= 10; $i++) { 
    // before a group of three, $counter is a multiple of three 
    if ($counter % 3 == 0) { 
     echo 'div <br />'; 
    } 

    // process the item then count it 
    echo 'do stuff <br />'; 
    $counter ++; 

    // after a group of three, $counter is a multiple of three 
    if ($counter % 3 == 0) { 
     echo 'end-div <br />'; 
    } 
} 

// close the last group if it is not complete 
if ($counter % 3 != 0) { 
    echo 'end-div <br />'; 
} 
+0

fonctionne parfaitement, merci! – pealo86

0

Il n'est pas nécessaire d'utiliser une variable $counter distincte, utilisez la variable $i dans la boucle for elle-même.

echo 'div <br />'; 
for ($i = 0; $i < 10; $i++) { 
    if($i != 0 && $i % 3 == 0) 
     echo 'end-div <br /> div <br />'; 
    echo 'do stuff <br />'; 
} 
echo 'end-div';