我正在尝试根据选择菜单中的城市选择生成用户的国家/地区。我使用关联数组生成了选择菜单。我想打印“$ city in $ country”但我无法正常访问$ country。这就是我所拥有的:
<?php
$cities = array("Tokyo" => "Japan", "Mexico City" => "Mexico",
"New York City" => "USA", "Mumbai" => "India", "Seoul" => "Korea",
"Shanghai" => "China", "Lagos" => "Nigeria", "Buenos Aires" => "Argentina",
"Cairo" => "Egypt", "London" => "England");
?>
<form method="post" action="5.php">
<?php
echo '<select name="city">';
foreach ($cities as $city => $country)
{
echo '<option value="' . $city . '">' . $city . '</option>';
}
echo '<select>';
?>
<input type="submit" name="submit" value="go" />
</form>
<?php
$city = $_POST["city"];
print ("$city is in $country");
?>
有什么想法吗?谢谢。
答案 0 :(得分:9)
您正试图从foreach循环中访问本地foreach变量$ country。你必须在循环中做到这一点。
或者您可以从城市数组中获取国家/地区:
$cities[$city];
答案 1 :(得分:1)
...
<?php
$city = $_POST["city"];
print ("$city is in ".$cities[$city]);
?>