我正在尝试构建一个带有城市名称列表的下拉菜单。对于返回值为“ true”的城市名称,我希望在同一页面上显示该文本为true的文本。如果选择的返回值是false,则我希望它也显示该值。我正在与表单操作和PHP一起尝试运行它,并完全失去了它。这是一个简单的任务,我一生都无法理解。
<select name="City">
<option value="Richmond">Richmond</option> //True//
<option value="Bowling Green">Bowling Green</option>//True
<option value="Manakin">Manakin</option>//false//
<option value="Emporia">Emporia</option>//false//
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['City']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; "and this location is Not served"
// Displaying Selected Value
}
?>
</body>
</html>
答案 0 :(得分:4)
我将使用一个保存值状态的数组,然后只需检查将确定状态的值即可。
<?php
$citys = [
'Richmond' => true,
'Bowling Green' => true,
'Manakin' => false,
'Emporia' => false
];
?>
<select name="City">
<?php foreach ($citys as $city => $avail): ?>
<option value="<?= $city ?>"><?= $city ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if (isset($_POST['submit'])) {
$selected_val = $_POST['City'] ?? ''; // Storing Selected Value In Variable
if (isset($citys[$selected_val])) {
echo "You have selected:".$selected_val." and this location is ".($citys[$selected_val] ? '' : 'Not').' served';
} else {
// error, city not in array
}
}
?>