我正在使用此 PHP 生成 0-9 的列表。
$counter = 0;
WHILE ($counter < 10)
{
print "counter is now " . $counter . "<br>";
$counter++;
}
我想改变它的工作方式。每第 3 次迭代,我想将打印的文本包装在 <div>
中如果可能的话。
所以最终我输出的代码是:
<div>
counter is now 0
counter is now 1
counter is now 2
</div>
<div>
counter is now 3
counter is now 4
counter is now 5
</div>
<div>
counter is now 6
counter is now 7
counter is now 8
</div>
<div>
counter is now 9
</div>
最佳答案
使用模数运算符,您可以每 3 次迭代拆分输出,但您仍然需要检查可能生成空 div
block 的 limit
值
<?php
$counter = 0;
$limit = 10;
print "<div>\n";
while ($counter < $limit) {
print "counter is now " . $counter . "<br>\n";
if (++$counter % 3 === 0 && $counter < $limit) {
print "</div>\n<div>\n";
}
}
print "</div>\n";
关于php - 每 3 次迭代中断 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28542890/