PHP:包装每组 3 个元素[重复]

问题描述 投票:0回答:3

我正在尝试弄清楚如何编写一个循环来包装每组 3 个元素。但是,对于最后一次迭代,它应该包装剩下的任何内容(无论是一个、两个还是三个元素)

所以基本上是这种模式:

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

这是我目前所处的位置:

<?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 ++;
  }

?>

这给了我以下内容:

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 

有人能看出我哪里出错了吗?

php loops for-loop iteration modulus
3个回答
3
投票

换句话说,您需要在每组三项之前写上

div
,在每组三项之后写上
end-div

// $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 />';
}

在线检查


1
投票
无需使用单独的

$counter

 变量,请在 
$i
 循环本身中使用 
for
 变量。

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';
    

1
投票
这就是我解决问题的方法

$total_items = 11; for( $i = 0; $i < $total_items; $i ++ ){ // get the starting element // the starting element will have ($i + 1 ) % 3 = 1 // all starting elements in the group will have a modulus of 1 when divided by 3 if( ( $i + 1 ) % 3 == 1 ){ echo "div <br />"; } echo "do stuff <br />"; // the group will either end where ($i + 1 ) % 3 = 0 // or at the end of the count // if total items are 2 then it will end at 2 if( ( $i + 1 ) % 3 == 0 || ( $i + 1 ) == $total_items ){ echo "end-div <br /><br />"; } }
我使用 w3schools PHP 编译器运行我的代码,请参阅屏幕截图

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.