一般来说,我是 PHP、HTML 和 Web 开发的新手。
我试图让一个列表框从关联数组中读取条目,我设法做到了。The problem is that, I can't seem to access the correct value, when an option is selected. 无论选择哪个选项,它似乎总是产生相同的响应(“伦敦”)。我尝试用 ["listBox"] 替换 $city,但输出是 'selected="selected"',$city 似乎更接近我想要的,所以我将其改回。
我花了很多时间试图找出原因,如果有人可以帮助我,我将不胜感激,在此先感谢您。
代码如下:
<!DOCTYPE html lang="en"/>`
<html>
<head>
<title>Array Section: ex5.php</title>
<charset = "utf-8">
</head>
<body>
<?php
// Create an associate array
$countriesWithCities = array(
"Japan" => "Tokyo",
"Mexico" => "Mexico City",
"USA" => "New York City",
"India" => "Mumbai",
"South Korea" => "Seoul",
"China" => "Shanghai",
"Nigeria" => "Lagos",
"Brazil" => "Sao Paulo",
"Egypt" => "Cairo",
"England" => "London"
);
?>
<form action="ex5b.php" method="POST" />
<h1>Ex5b.php </h1>
<h3>"listBox">Please choose a country from the list box. </h3>
<select name="listBox" id="listBox" size="9" >
<?php foreach ($countriesWithCities as $individualCountry => $city) { ?>
<option value= <?php $city; ?> selected="selected">
<?php echo $individualCountry;
>
} ?></option>
</select>
<input type="submit" name="submitButton" id="submitButton" value="Submit form" />
<form>
<?php
if (isset($_POST["submitButton"])) {
echo "You chose " . $city;
}
?>
</body>
</html>