简体   繁体   English

While循环-可能只有6个循环?

[英]While loop - possible to have only 6 loops?

This is my code, I would like it so that it only does the first 6 array items. 这是我的代码,我希望它只执行前6个数组项。 Also, how would I write a loop for everything AFTER the 6 first array items? 另外,在第一个6个数组项之后,我该如何为所有内容编写循环?

while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {

    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}

Try the following for your first request: 对于您的第一个请求,请尝试以下操作:

$count = 0;
while($servdescarrayrow = mysql_fetch_array("servdescarray")) {
  $count++;
  echo "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
  if($count == 6){
    break;
  }
}

Then you could do the below for part 2: 然后,您可以对第2部分执行以下操作:

$count = 0;
while($servdescarrayrow = mysql_fetch_array("servdescarray")) {
  $count++;
  if($count > 6){
    echo "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
  }
}

Alternatively (and better) is to use LIMIT in your SQL query 或者(更好)是在SQL查询中使用LIMIT

To have just the first 6 rows, the best way is to use LIMIT in your sql statement in this way. 要仅具有前6行,最好的方法是以这种方式在sql语句中使用LIMIT

SELECT *
FROM table
WHERE condition
LIMIT 6

If you want to have a loop that print the first 6 rows and then another loop that will print the remaining rows use the solution provided by nickb . 如果要循环打印前6行,然后循环打印其余行,请使用nickb提供的解决方案。

for( $i = 0; $i < 6; $i++)
{
    $servdescarrayrow = mysql_fetch_array("servdescarray");
    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}

To get the remaining entries (since the result set will remember where it left off): 要获取剩余的条目(因为结果集将记住它保留的位置):

while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {

    ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
}
SELECT * 
FROM table 
WHERE condition 
OFFSET 6 

this query will get everything after the first 6. I'm assuming you're using mysql. 该查询将在前6个之后得到所有信息。我假设您使用的是mysql。

Adding a single loop approach. 添加单循环方法。 To keep it simple and readable, us a count variable $rowNum to determine what to do in your loop. 为了使其简单易读,我们使用一个计数变量$rowNum来确定循环中要执行的操作。

    $rowNum = 0;
    while ($servdescarrayrow = mysql_fetch_array("servdescarray")) {
        $rowNum++;

        if($rowNum<=6)
        {
             ECHO "<fieldset>Services: ".$servdescarrayrow."</fieldset>";
        }
        else
        {
            // Code for other items
        }
    }

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

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