![](/img/trans.png)
[英]PHP insert <div> and line shift after every 10th DB element in foreach loop
[英]How can I loop through a table skipping every 11th row while doing something on every 10th loop?
這是我認為應該如何工作的思考過程。
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) && ($row % 11 != 0)) {
$counter++;
if ($counter % 10 == 0) {
// Do something.
}
}
}
它應如何工作的示例:
第1行=計數器1
第2行=計數器2
第3行=計數器3
第4行=計數器4
第5行=計數器5
第6行=計數器6
第7行=計數器7
第8行=計數器8
第9行=計數器9
第10行=計數器10
第11行=跳過
第12行=計數器11
第13列=計數器12
第14行=計數器13
第15行=計數器14
第16行=計數器15
第17行=計數器16
第18行=計數器17
第19行=計數器18
第20行=計數器19
第21行=計數器20
第22行=跳過
第23行=計數器21
等等
為了進一步參考,這是我編寫的完整代碼,以提醒用戶在我的網上商店中,如果他們的購物車中有10張票,那么如果添加了這張票,他們將免費獲得一張。 謝謝雅加爾
$fancyCounter = 1;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$rawCounter++;
if ($rawCounter % 11 !== 0) {
$fancyCounter++;
}
else {
$fancyCounter = 1;
}
}
}
$result->close();
if ($fancyCounter % 11 == 0) {
$freeTicketAvailable = 1;
} else {
$freeTicketAvailable = 0;
}
嘗試這個,
<?php
$counter = 1;
while ($counter <= 33) {
if ($counter % 10 == 0) {
// On 10.
echo "Do Something<br/>";
} else if ($counter % 11 == 0) {
// On 11.
echo "Skip<br/>";
} else {
// Other numbers.
echo $counter . "<br/>";
}
$counter++;
}
?>
您需要替換while();
內部的條件while();
適合你。
產量
1 2 3 4 5 6 7 8 9 Do Something Skip 12 13 14 15 16 17 18 19 Do Something 21 Skip 23 24 25 26 27 28 29 Do Something 31 32 Skip
這應該做。 您試圖在while條件中將數組($ row)除以數字,即使在PHP中也可能未定義;)
if ($result->num_rows > 0) {
$skipCounter = 0;
$tenCounter = 0;
$counter = 0;
while($row = $result->fetch_assoc()) {
++$skipCounter;
if ($skipCounter == 11) {
$skipCounter = 0;
continue;
}
++$counter
++$tenCounter;
echo "Counter: ".$counter;
if ($tenCounter == 10) {
$tenCounter = 0;
echo "Do something";
}
}
}
在這里,有一個$rawCounter
來計數迭代的行,還有一個$fancyCounter
來保持行的計數與您發布的方式相同。
while($row=$result->fetch_assoc()){
$rawCounter++;
if ($rawCounter%11!==0){
$fancyCounter++;
}
if ($rawCounter%10===0){
//Do Something
}
}
這是一個給出示例輸出的示例。
如果需要將行號和計數器號分開,則還可以使用$counter
和$skipCount
,並且始終遞增$counter
,僅對$counter%11==0
遞增$skipCount
並獲得所需的計數器計數(即Row 12 = Counter 11, Row 23 = Counter 21
), echo "Row {$counter} = Counter ".($counter-$skipCount)
使用echo "Row {$counter} = Counter ".($counter-$skipCount)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.