简体   繁体   中英

Getting rid of duplicates in PHP while loop

So here's my php code:

$sql1 = "SELECT year FROM reports ORDER BY year DESC";
$res1 = mysql_query($sql1);
while($row = mysql_fetch_array($res1)) {
    $selectYear = "
        <select id='select_year'>
            <option value='".$row['year']."'>".$row['year']."</option>
        </select>
    ";
}

What I want it to do is just output one year instead of what its doing now which is outputting every single year and there is one entry for each month of the year so there are 12 entries with the same year so my html is this:

<select id='select_year'>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2013'>2013</option>
    <option value='2012'>2012</option>
</select>

But this is what I actually want:

<select id='select_year'>
    <option value='2013'>2013</option>
    <option value='2012'>2012</option>
</select>

This is to sort through all the results by year so that the user can just use the select to select which year they want to view.

There are lots of ways of doing this, but the easiest is probably:

$sql1 = "SELECT DISTINCT year FROM reports ORDER BY year DESC";

With DISTINCT , the database will only return one of each value. Then you don't have to waste any resources processing data on the PHP side.

@Thomas Kelley has given the perfect answer above.

However, if you insist on PHP solution. You can do it as follows.

$res1 = mysql_query($sql1);
$placeHolder = ",";
while($row = mysql_fetch_array($res1)) {
    if ( strpos($placeHolder , $row['year']) )
        continue;
    $placeHolder .= $row['year'] .',';
    $selectYear = "
        <select id='select_year'>
            <option value='".$row['year']."'>".$row['year']."</option>
        </select>
    ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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