[英]while loop inside for loop PHP
i'm trying to display a while loop depending on the parameters in my for loop. 我试图根据我的for循环中的参数显示while循环。 for example, my for loop says to loop through 5 times, the data inside while loop should also be displayed 5 times.
例如,我的for循环说要循环5次,而while循环中的数据也应该显示5次。 however, when i tested my code, the data inside while loop only displays once.
但是,当我测试代码时,while循环中的数据仅显示一次。 i'm not sure if i did the iteration correctly.
我不确定我是否正确进行了迭代。 here is a snippet of my nested loop.
这是我的嵌套循环的一小段。
for($i=0; $i<$count; $i++){
echo "COUNT: ".$i."<br>";
while($data=mysqli_fetch_array($res)) {
echo "INSIDE WHILE".$i."<br>";
}
}
so if my $count = 3, the output of this code is 因此,如果我的$ count = 3,则此代码的输出为
0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
INSIDE WHILE0
1
2
and what i want is for "INSIDE WHILE" to also be displayed between 1 and 2. 我想要的是“ INSIDE WHILE”也要显示在1到2之间。
Just add mysqli_data_seek after the while loop: 只需在while循环后添加mysqli_data_seek即可 :
for($i=0; $i<$count; $i++){
echo "COUNT: ".$i."<br>";
while($data=mysqli_fetch_array($res)) {
echo "INSIDE WHILE".$i."<br>";
}
mysqli_data_seek($res, 0);
}
$data=mysqli_fetch_array($res, MYSQLI_ASSOC);
for($i=0; $i<$count; $i++){
echo "COUNT: ".$i."<br>";
foreach ($data as $current_data){
echo "INSIDE WHILE".$i."<br>";
echo $current_data[name]; //name is the field name.
}
}
You can move the fetch on top, so you don't have to reset the cursor of the fetch. 您可以将提取操作移到最上面,因此不必重置提取操作的光标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.