如果在选择框中相同,则回显结果一次

问题描述:

I have 'city' field in database which contains postal code and city name like this: '12345 City' Now I need to get just those cities and populate a select field. With code below i get duplicate cities (if there is '12345 Chicago' and '54321 Chicago' I get two Chicago options), how to do something like mysql group by or distinct in php?

while ($re = mysql_fetch_assoc($rez))
  {
    $city= $re["city"];
    $city= preg_replace("/[0-9]/", "", $city);
    $city= trim($city);

     if ($city==""){echo "";}
     else if ($_SESSION['sess']==$city){
      echo "<option value={$_SESSION['sess']} selected=selected>{$_SESSION['sess']}</option>";
        }
     else echo "<option value=$city>$city</option>";
  }

$city_array = array();
while ($re = mysql_fetch_assoc($rez))
  {
    $city= $re["city"];
    $city= preg_replace("/[0-9]/", "", $city);
    $city= trim($city);

    $city_array[] = $city;
  }
$city_array = array_unique($city_array);

then run the foreach loop for $city_array

You can store $city as key in an array. Since keys in an array are unique you will not get any duplicate values.

$ar = array();
while($re = mysql_fetch_assoc($rez)) {
    $city= $re["city"];
    $city= preg_replace("/[0-9]/", "", $city);
    $city= trim($city);

    $ar[$city]=0;
}

Then you can use foreach loop to iterate through the key values.

foreach($ar as $key =>$value) {
    if($key == "") {
        echo "";
    }
    else if ($_SESSION['sess']==$key){
        echo "<option value={$_SESSION['sess']} selected=selected>{$_SESSION['sess']}</option>";
    }
    else {
        else echo "<option value=$key>$key</option>";
    }
}