【问题标题】:How to return PHP array value from key?如何从键返回 PHP 数组值?
【发布时间】:2011-07-30 19:21:01
【问题描述】:

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

有什么想法吗?谢谢。

【问题讨论】:

    标签: php arrays loops


    【解决方案1】:

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

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

    $cities[$city];
    

    【讨论】:

      【解决方案2】:
      ...
      <?php
      $city = $_POST["city"];
      
      print ("$city is in ".$cities[$city]);
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多