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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件