提问人:Tony Poli 提问时间:5/5/2023 最后编辑:Tony Poli 更新时间:5/7/2023 访问量:76
如果 while 循环中存在条件,如何每两个周期递增变量
How to increment variable every two cycle if condition exist in a while loop
问:
我有一个来自数据库的数组进入一个循环“while”循环,如果两行具有相同的值增量 +1 一个变量,我需要每两个周期一次。
如果有一个赢家,则每 2 个周期,如果有一个赢家(vincente),则紧接着在赢家之后,$cnt变量增加 1,如果有一个赢家(vincente),则紧接在输家(perdente)之后,没有增量,整个数组,一次 2 行。
$cnt=0;
While ($row = mysqli_fetch_array($res)){
if ($row['result']=="vincente"){
}
else {
}
}
我尝试这样做,但不想继续。
答:
0赞
Фарид Ахмедов
5/7/2023
#1
您需要同时检查两个项目。以下是如何做到这一点的示例。
// making a Generator, that will return pair of elements on each iteration
function fetchPairs($result) {
// initialize array, which will store elements
$pair = [];
while ($row = mysqli_fetch_array($result)) {
// add each element in array
$pair[] = $row;
// if there is 2 elements..
if (count($pair) === 2) {
// ..yield them and..
yield $pair;
// ..clear array
$pair = [];
}
}
}
$count = 0;
// in this `foreach` each iteration now returns pair of two elements;
foreach (fetchPairs($res) as [$first, $second]) { // you can use $pair instead of destructing list into $first and $second varialbes
// check both items are 'vincente'
if ($first['result'] === 'vincente' && $second['result'] === 'vincente') {
$count += 1;
}
}
评论
$cnt
$cnt = floor($cnt/2)
SELECT FLOOR(COUNT(*)/2.0) as winning_count FROM yourtable WHERE result = 'vicente'
if(0 === $cnt % $n) {}