如何从键返回PHP数组值?

如何从键返回PHP数组值?,php,arrays,loops,Php,Arrays,Loops,我试图根据选择菜单中的城市选择生成用户的国家/地区。我已经使用关联数组生成了选择菜单。我想打印“$city在$country中”,但我无法正确访问$country。这就是我所拥有的: <?php $cities = array("Tokyo" => "Japan", "Mexico City" => "Mexico", "New York City" => "USA", "Mumbai" => "India", "Seoul" => "Korea", "Sh

我试图根据选择菜单中的城市选择生成用户的国家/地区。我已经使用关联数组生成了选择菜单。我想打印“$city在$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");
?>


有什么想法吗?谢谢。

您正在尝试从foreach循环中访问本地foreach变量$country。你必须在循环中这样做

或者你可以从城市阵列中获取国家信息,如:

$cities[$city];
。。。
...
<?php
$city = $_POST["city"];

print ("$city is in ".$cities[$city]);
?>