我正在使用这个PHP生成0-9的列表。
$counter = 0;
WHILE ($counter < 10)
{
print "counter is now " . $counter . "<br>";
$counter++;
}
我想改变它的运作方式。每次第三次迭代,如果可能的话,我想将我的打印文本包装在<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>
答案 0 :(得分:1)
使用模数运算符,您可以每3次迭代拆分输出,但仍需要检查可能生成空limit
块的div
值
<?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";
答案 1 :(得分:0)
使用modulus执行此操作
while($counter < 10) {
if($counter % 3 == 0) {
//Do something for the third row
}
$counter++;
}
答案 2 :(得分:0)
尝试:
$counter = 0;
$block_count = 0;
echo "<div>";
while ($counter < 10) {
if ($block_count === 3) {
echo "</div><div>";
$block_count = 0;
}
echo "counter is now " . $counter . "<br>";
$block_count++;
$counter++;
}
echo "</div>";
答案 3 :(得分:0)
我不知道php,但我认为逻辑是一样的:
$counter2 =0; //count to 10
$stopIteration =10;
WHILE($counter2<$stopIteration){
print "<div>";
$counter1 =0; //count to 3
WHILE($counter1<3){
print "counter is now".$counter2."<br>";
$counter1++;
$counter2++;
}
print "</div>";
}
答案 4 :(得分:0)
我发现这种任务的最佳故障保护方法是将所有数据(在这种情况下,所有10个打印的字符串)分组在数组中,而不是将这个数组分成块http://php.net/manual/en/function.array-chunk.php,然后你可以工作使用这个新数组,因为它被分成块,其中每个块不大于例如3.但是你的输出不会失败,因为模态只有在你的元素模数总数为0时才有效,在这种情况下10个元素将失败,因为在最后一个循环中,模态语句不会起作用。
当不存在除以3的总元素时,这将添加故障保护。
$counter = 0;
$arr = array();
WHILE ($counter < 10)
{
$arr[] = "counter is now " . $counter . "<br>";
$counter++;
}
$arr = array_chunk($arr, 3);
foreach ($arr as $chunk) {
//wrap each chunk into div
echo "<div>"
foreach ($chunk as $string) {
//print your string here
}
echo "</div>"
}