如何从键返回 PHP 数组值?

发布于 2024-11-27 12:01:09 字数 824 浏览 1 评论 0原文

我正在尝试根据选择菜单中的城市选择生成用户的国家/地区。我使用关联数组生成了选择菜单。我想打印“$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情绪操控生活 2024-12-04 12:01:09

您正尝试在 foreach 循环之外访问本地 foreach 变量 $country。您必须在循环内执行此操作。

或者您可以从城市数组中获取国家/地区,例如:

$cities[$city];

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 :

$cities[$city];
魂ガ小子 2024-12-04 12:01:09
...
<?php
$city = $_POST["city"];

print ("$city is in ".$cities[$city]);
?>
...
<?php
$city = $_POST["city"];

print ("$city is in ".$cities[$city]);
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文