简体   繁体   English

确定while循环中有多少个项目

[英]Determine how many items in a while Loop

How can I determine how many items there are in a while Loop? 如何确定while循环中有多少个项目?

Example : 范例

while ($row = mysql_fetch_array($query)){


echo "<strong>name:</strong> ".$row['name']."<br>";
echo "<strong>country:</strong> ".$row['country']."<br>";
echo "<strong>house:</strong> ".$row['house']."<br>";
}

Output : 输出

Name: Example Name 名称:示例名称

Country: Germany 国家:德国

House : Example street 1 房屋 :示例街1

House 2 : Example street 3 房屋2 :示例街道3

House 3 : Example street 5 房屋3 :示例街5

I need to know this because I want to add the number behind house 2/3 as a variable. 我需要知道这一点,因为我想将2/3号房屋后面的数字添加为变量。 Should I place the while loop in a for loop so I can add: 我应该将while循环放在for循环中,这样我可以添加:

$housenumber++;

echo "<strong>house ".$housenumber.":</strong> ".$row['house']."<br>";

You can use 您可以使用

$total = mysql_num_rows($query);

To find out the total number of rows in the while loop. 找出while循环中的总行数。

Declare this before your while loop and after $query is defined. 在while循环之前和$query定义之后声明它。

However, I should point out that mysql_query and mysql_num_rows are deprecated and you should use MySQLi or PDO. 但是,我应该指出,不建议使用mysql_querymysql_num_rows ,而应使用MySQLi或PDO。 See here for more information. 有关更多信息,请参见此处

Wrapping a loop inside a loop won't accomplish what you're getting at (or it might, but it's just needless overkill). 在一个循环中包装一个循环将无法完成您所要获得的功能(或者可能会完成,但这只是不必要的过度杀伤力)。 Incrementing a variable works in any kind of loop, so you could just write: 递增变量可以在任何循环中使用,因此您可以编写:

$housenumber = 0;
while ($row = mysql_fetch_array($query)){
  echo "<strong>name:</strong> ".$row['name']."<br>";
  echo "<strong>country:</strong> ".$row['country']."<br>";
  echo "<strong>house ".$housenumber.":</strong> ".$row['house']."<br>";
  $housenumber++;
}

As Tom is saying you're using deprecated functions to retrieve MySQL data, so your code will cease to work in future versions of PHP. 正如Tom所说的那样,您正在使用不赞成使用的函数来检索MySQL数据,因此您的代码将在以后的PHP版本中停止工作。

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

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