dongyuruan2957 2014-02-24 01:29
浏览 51
已采纳

从多维数组创建下拉列表

I got this array:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => tomato
        )

    [1] => Array
        (
            [id] => 2
            [name] => carrot
        )

    [2] => Array
        (
            [id] => 3
            [name] => apple
        )

)

I want to print each key/value pair in an HTML form, like so:

<select>
    <option value="1">tomato</option>
    <option value="2">carrot</option>
    <option value="3">apple</option>
</select>

So, I'm using a foreach loop to iterate over the three items in the outer array and then try to print the items in the inner array on a single line. I'm stuck with the last bit. The closest I've got so far is this:

foreach ($food_opts as $key => $value) {
    foreach ($value as $k => $v) {
        echo '<pre>' . $v . '</pre>';
    }
}

This retrieves the data I need but not in a usable format:

1
tomato
2
carrot
3
apple

In short, how do you target individual items in an inner array? Something like:

foreach ($food_opts as $key => $value) {
    foreach ($value as $k => $v) {
        echo '<pre>' . $v[0] . ' - ' . $v[1] . '</pre>';
    }
}

I understand why the above code doesn't work but can't figure out how to get the data how I want it.

  • 写回答

2条回答 默认 最新

  • douyingbei1458 2014-02-24 01:33
    关注

    You don't need a nested foreach here. Just do:

    foreach ($food_opts as $key => $arr) {
        echo '<option value="'.$arr['id'].'">'.$arr['name'].'</option>', PHP_EOL;
    }
    

    Or, you can use printf() for a more cleaner approach:

    foreach ($food_opts as $key => $arr) {
        printf('<option value="%s">%s</option>', $arr['id'], $arr['name']).PHP_EOL;
    }
    

    The printf() family of functions uses % character as a placeholder. %s means "take the next argument and print it as a string". Similarly, %d means "take the next argument and print it as an int".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi