简体   繁体   English

while循环中的自动增量变量

[英]Auto increment variable in while loop

I have a variable that is a string with divs in html. 我有一个变量,它是一个字符串,在html中有divs

I'm trying to include a number in it that starts at one and auto increments so that each div is numbered in ascending order. 我正在尝试在其中包含一个从1开始并自动递增的数字,以便每个div按升序编号。

This is my while: 这是我的时间:

while ($row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$catname9 = $row9["catname"];
$statusid9 = $row9["id"];
$i = 1;

This is my string that I echo repeatedly until it reaches the end of my called SQL table: 这是我的字符串,我反复回应,直到它到达我调用的SQL表的末尾:

$list9 .= '<div id="each9" style="margin-top:3px" onclick="moveTo(\'.main\', '.$i.');"></div>

Then I echo: 然后我回应:

<?php echo $list9; ?>

So how do I make the first one 1 then the second repeat 2 and the third repeat 3? 那么如何制作第一个1然后第二个重复2和第三个重复3?

Set up your while loop like so: 像这样设置你的while循环:

$i = 1;
while ($row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

    // looped logic here

    $i++;
}

The important thing here is to initialize the counter before the loop, and increment it on each iteration. 这里重要的是在循环之前初始化计数器,并在每次迭代时递增它。

You can also increment it by other amounts if you want. 如果需要,您还可以将其增加其他金额。 Just replace $i++ with $i += 2 ; 只需用$i += 2替换$i++ ;

Initialize the variable by $i=1 like: 通过$i=1初始化变量,如:

$i = 1; 
while ($row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {

echo $i; // will print 1,2,3 to number of count.
$i++;
}

First off, you will have to declare the index variable before the while loop. 首先,您必须在while循环之前声明索引变量。
If you declare it inside, it will be a new variable each time it iterates. 如果你在里面声明它,它每次迭代时都是一个新的变量。
When that is done, you will need to increment the variable for each iteration, this can be done by either $i++ or $i+=1 . 完成后,您需要为每次迭代增加变量,这可以通过$i++$i+=1

If you wish it to start with 1 and the increase, set it to 1 from start and increase it by 1 at the end of the loop. 如果您希望以1开始并增加,请从开始将其设置为1,并在循环结束时将其增加1。

Like: 喜欢:

$index = 1;
while(...) {
  // Do stuff...
  $index++; // increase.
}
$i = 0;
while ($i < $row9 = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $i++;
} 
echo $i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM