简体   繁体   English

PHP循环x次,使用while和if

[英]PHP loop x number of times, using while and if

So this has been driving me nuts for several days. 因此,这已经让我发疯了好几天。 I've tried THIS and THAT but nothing is working. 我已经试过THAT但没有什么工作。 Here's the basic rundown: 这是基本的摘要:

I have a MySQL database with 200 or so locations. 我有一个200多个位置的MySQL数据库。 The user enters their zip code, and I want to give them 6 random locations within 100 miles of home. 用户输入他们的邮政编码,我想给他们在100英里范围内的6个随机位置。 Everything works great, except I can't get it to limit the results to 6. It will give me ALL the results for <100. 一切都很好,除非我无法将结果限制为6。它将为我提供<100的所有结果。 When I try the code below (adding the for ($x=0...) bit), I get the same result, only each one repeats 6 times before listing the next one. 当我尝试下面的代码(添加for ($x=0...)位)时,我得到相同的结果,只有每个重复重复6次,然后列出下一个。 Here's the pertinent code that returns all the locations. 这是返回所有位置的相关代码。 Any help would save me from throwing my computer out the window. 任何帮助都可以避免我将计算机扔出窗户。

$sql = "SELECT * FROM locations ORDER BY RAND()"; 
$result = mysql_query($sql, $dbase2);

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

$city = $row['city']; 
$id= $row['id'];
$miles = calculateDistance($lat, $lon, $point2_lat,$point2_lon); 

  if ($miles < "100")
      { for ($x=0; $x<6; $x++){
       echo $city . " is about " . round($miles) . " miles away.<br />";
         };
      };           
  };

Like I said, for the sake of this post, I tried to pare it down to the important bits. 就像我说的那样,出于这篇文章的缘故,我试图将其缩减为重要的部分。 Let me know if something vital is missing from my example. 让我知道我的示例中是否缺少重要的内容。

The following change should do it: 进行以下更改即可:

$count = 0;
while (($row = mysql_fetch_array($result)) && ($count < 6))
    {

    $city = $row['city']; 
    $id= $row['id'];
    $miles = calculateDistance($lat, $lon, $point2_lat,$point2_lon); 

    if ($miles < 100.0) {
       echo $city . " is about " . round($miles) . " miles away.<br />";
       $count = $count + 1;
      };           
  };

There are more elegant ways... 还有更多优雅的方法...

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

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