如何从键返回 PHP 数组值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6885472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return PHP array value from key?
提问by dmubu
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:
我正在尝试根据选择菜单中的城市选择生成用户的国家/地区。我使用关联数组生成了选择菜单。我想打印“$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");
?>
Any ideas? Thank you.
有任何想法吗?谢谢你。
回答by Spyros
You are trying to access the local foreach variable $country out of the foreach loop. You have to do that inside the loop.
您正在尝试从 foreach 循环中访问本地 foreach 变量 $country。您必须在循环内执行此操作。
Or you could just get the country from the cities array like :
或者你可以从城市数组中获取国家,例如:
$cities[$city];
回答by DevelRoot
...
<?php
$city = $_POST["city"];
print ("$city is in ".$cities[$city]);
?>