如何从键返回 PHP 数组值?
我正在尝试根据选择菜单中的城市选择生成用户的国家/地区。我使用关联数组生成了选择菜单。我想打印“$city is 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");
?>
什么想法吗?谢谢。
I am trying to generate a user's country based on the city selection in a select menu. I have generated the select menu using an associative array. I want to print "$city is in $country" but I cannot access the $country properly. This is what I have:
<?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");
?>
Any ideas? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正尝试在 foreach 循环之外访问本地 foreach 变量 $country。您必须在循环内执行此操作。
或者您可以从城市数组中获取国家/地区,例如:
You are trying to access the local foreach variable $country out of the foreach loop. You have to do that inside the loop.
Or you could just get the country from the cities array like :