简体   繁体   English

PHP停止在循环中两次回显数据

[英]PHP stop data from being echoed twice in loop

Consider the following simple code, which should stop the same value being echoed twice 考虑下面的简单代码,该代码应停止将相同的值回显两次

$sql = "SELECT * FROM events 
        WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby' 
        ORDER BY event_date ";

$lasttournament=""
echo'<select name="tournament" />';
 while($played>$venue){
   $tournament = $row['tournament'];

        if($tournament !== $lasttournament){
          $lasttournament = $tournament;
          echo'<option value="'.$tournament.'">'.$tournament.'</option>';           
         }//if 
      }//while

However my code is not giving the desired result, as you can see from image below. 但是,我的代码没有给出期望的结果,如下图所示。

在此处输入图片说明

Im obviously missing something, as each tournament should be displayed only once 我显然遗漏了一些东西,因为每个锦标赛只能显示一次

Try with distinct if you need the tournament field only - 与尝试distinct ,如果你需要的tournament只有场-

SELECT DISTINCT tournament FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby'
    ORDER BY event_date

Or try with group by - 或尝试group by -

SELECT * FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby'
    GROUP BY tournament 
    ORDER BY event_date
$sql = "SELECT DISTINCT tournament FROM events 
    WHERE event_date BETWEEN $curDate AND $date AND sport_type ='Rugby' 
    ORDER BY event_date ";

It seams you only need tournament from the sql and with this you will only get each tournament once. 它表明您只需要从sql中获得锦标赛,并且您每次只能获得一次锦标赛。

As other replied filtering values into sql using DISTINCT or GROUP BY is the right solution, you have a cleaner code and execute less iterations. 由于使用DISTINCT或GROUP BY将其他已过滤的值复制到sql是正确的解决方案,因此您的代码更简洁,迭代次数也更少。

Anyway your code wasn't working because the variable $lasttournament is overwritten every cycle with the last value so your condition work only if the same values are consecutive each other. 无论如何,您的代码都无法正常工作,因为变量$ lasttournament在每个循环中都被最后一个值覆盖,因此只有当相同的值彼此连续时,条件才起作用。

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

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