问问题
1096 次
5 回答
4
//first you have a specific city of a user
$user_city = 'city-name';
//Then you have a list of all cities available (probably from the database,
// but I use array here as an example)
$cities = array('city1','city2','city3');
<select name="cities">
<?php
foreach ( $cities as $city ) {
if ( $city == $user_city ) {
echo "<option value='".$city."' selected>$city</option>";
} else {
echo "<option value='".$city."'>$city</option>";
}
}
?>
</select>
于 2012-12-27T10:19:59.637 回答
1
只需检查数据库中的值并使用 javascript 或 php 将选定的选项添加到该选项
<option value="murree" selected >Murree</option>
于 2012-12-27T10:13:53.857 回答
1
将您的城市列表放入数组而不是硬编码的 HTML。
循环遍历列表并输出option
每个元素。
当您这样做时,与从数据库中检索到的值进行比较。selected
如果匹配则添加。
于 2012-12-27T10:14:23.387 回答
0
一种可能的解决方案可能是将您的代码结构更改为以下内容:
// hardcoded cities or perhaps loaded from elsewhere
$cities = [
"nc" => "New city...",
"quetta" => "Quetta",
"karachi" => "Karachi"
// ...
];
// user's city fetched from the database
$userCity = "quetta";
echo '<select name="cities">';
foreach ($cities as $key => $value)
{
echo '<option ' . ($userCity === $key ? 'selected' : '') . ' value="' . $key . '">' . $value . '</option>';
}
echo '</select>';
于 2012-12-27T10:24:37.120 回答
-1
于 2012-12-27T10:20:51.860 回答