简体   繁体   English

如何限制PHP While循环的输出?

[英]How Can I Limit the Output from a PHP While Loop?

I have a while loop running that is returning values from a MYSQL table. 我正在运行while循环,该循环从MYSQL表返回值。 It returns about 90 entries from the query. 它从查询中返回大约90个条目。 My hope is to be able to break these 90 values up and display them in groupings of 5. This may sound confusing so let me share some code samples to help clarify: 我希望能够分解这90个值,并以5个分组的形式显示它们。这听起来可能令人困惑,所以让我分享一些代码示例以帮助阐明:

$con = mysql_connect("host", "username", "password") or die ("Unable to connect to server");
mysql_select_db("database") or die ("Unable to select database");
$sql = mysql_query("SELECT * FROM `table` WHERE column IS NOT NULL AND column <> ''");

Here I am pulling the values out that I need from the table... 在这里,我从表中提取了我需要的值...

while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$column=$row['column'];

echo $id . '<br>';
echo $column . '<br>';

}   

At this point, I have run the loop and get the display of all 90 entries. 至此,我已经运行了循环并显示了所有90个条目。 How can I pull the values out and display them in smaller chunks? 如何提取值并以较小的块显示它们? If I use the looped values outside of the while loop, it just gives me the last value from the set. 如果我在while循环之外使用循环值,它只会给我最后一组值。 Is there a simple way to use the unique $id value from the column to get a specific grouping within the loop? 有没有一种简单的方法可以使用列中的唯一$id值在循环中获取特定的分组?

This will add more br's and a hr after each 5 records: 这将在每5条记录之后增加br和一个小时:

$cnt = 0;
while($row=mysql_fetch_array($sql))
{

  $id=$row['id'];
  $column=$row['column'];

  echo $id . '<br>';
  echo $column . '<br>';

  if($cnt % 5 == 0) echo "<br><br><hr><br><br>";

  $cnt++;
}   

Here is one (not very sophisticated) approach you could take: 您可以采用以下一种方法(不是很复杂):

$group_size = 5;
$tracking_variable = 0;
while ($row = function_to_fetch_row()) {
    if ($tracking_variable == 0) {
        // logic for the start of a grouping
    }
    // logic to display the row
    $tracking_variable = ($tracking_variable + 1) % $group_size;
    if ($tracking_variable == 0) {
        // logic for the end of a grouping
    }
}
if ($tracking_variable > 0) {
    // logic for the end of the final grouping
}

You want to save this data in a variable, and reference it outside of the loop. 您想将此数据保存在变量中,并在循环外引用它。

Try this: 尝试这个:

$data = array();
while($row=mysql_fetch_array($sql))
{
    $data[$row['id']] = $row['column'];
}

And now you can just display specific rows: 现在,您可以只显示特定的行:

print $data[$someRow];

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

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