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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题