doupacan2098 2013-11-24 07:26
浏览 55
已采纳

使用foreach PHP回显嵌套数组

I have seen many similar issues but none that can help explain my issue. I have an array called cities, with a nested array for the state that has the cities of that state. It looks like this:

$cities = array(
    "ca" => array(
        "los-angeles" => "Los Angeles"
    ),
    "wa" => array(
        "bellingham" => "Bellingham",
        "seattle" => "Seattle",
        "tacoma" => "Tacoma"
    )
);

My PHP code to display many HTML select fields:

<?php
foreach ($cities as $state) {
    echo "<select name='city' id='" . $state . "'>";
    foreach ($state as $city => $name) {
        echo "<option value='" . $city . "'>" . $name . "</option>";
    }
}
?>

The id of the select is always Array. How can I use the key, like "ca" or "wa"?

  • 写回答

4条回答 默认 最新

  • doubushi0031 2013-11-24 07:35
    关注

    The problem is that you should be using the array key for the select on the states. Here is my revision of your code. Note that I explicitly have named state_key and state_value as well as city_key and city_value. Naming things explicitly like this helps in debugging. I also added a closing </select> element so the content renders correctly.

    foreach ($cities as $state_key => $state_value) {
    
        echo "<select name='city' id='" . $state_key . "'>";
        foreach ($state_value as $city_key => $city_value) {
            echo "<option value='" . $city_key . "'>" . $city_value . "</option>";
        }
        echo "</select>";
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?