从一个多维阵列创建一个下拉列表 [英] Create a dropdown list from a multi-dimensional array
问题描述
我得到这个数组:
Array
(
[0] => Array
(
[id] => 1
[name] => tomato
)
[1] => Array
(
[id] => 2
[name] => carrot
)
[2] => Array
(
[id] => 3
[name] => apple
)
)
我要打印的每个键/值对在HTML表单,像这样:
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>
所以,我使用foreach循环遍历数组外的三个项目,然后尝试打印在一行内数组中的项目。我被困在最后一位。到目前为止,我所得到的最接近是这样的:
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>';
}
}
我明白为什么上面code不工作,但无法弄清楚如何获得数据我怎么想的那样。
I understand why the above code doesn't work but can't figure out how to get the data how I want it.
推荐答案
您不需要嵌套的foreach
在这里。只要做到:
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;
}
或者,您可以使用 的printf()
为一个更简洁的方法:
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;
}
的的printf()
家庭功能用途%
字符作为占位符。 %S
的意思是把下一个参数并打印它作为一个字符串。同样,%d个
的意思是把下一个参数,并打印成int类型。
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".
这篇关于从一个多维阵列创建一个下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!