在codeigniter中使用数组作为值 [英] Dropdown in codeigniter using array as values
问题描述
我在$ categories变量中返回了一个result_array(),现在我想创建一个下拉菜单。但是如果我直接使用这个变量,数组的所有元素都将被显示。不过,我只想显示名称并将其ID保留为值。如何做到这一点?
I have returned a result_array() in $categories variable and now I want to create a dropdown menu. But if I directly use the variable, all the elements of the array are going to be displayed. However I just want to display the name and keep its id as value. How do i do it?
$options = $categories;
echo form_dropdown('category', $options);
我想要类似于
I want something like
<select name="category">
<option value="1"> ABC </option>
.....
<option value="10"> NNNC </option>
</select>
推荐答案
$ options数组中的键不是实际的ID数据库行。
Keys in your $options array are not actual ID's of database rows.
所以你的$ options数组看起来像这样:
So your $options array looks like this:
Array(
'0' => array('id'=>'10', 'value'=>'someval1'),
'1' => array('id'=>'22', 'value'=>'someval2'),
'2' => array('id'=>'36', 'value'=>'someval3'))
要看到这个,请放入 print_r($ options);
在echo调用之前。
To see this, put print_r($options);
before echo call.
为了实现真正的下拉,您应该使辅助函数看起来像这样:
To make real dropdown you should make helper function that looks like this:
function my_form_dropdown($name, $result_array){
$options = array();
foreach ($result_array as $key => $value){
$options[$value['id']] = $value['value'];
}
return form_dropdown($name, $options);
}
这篇关于在codeigniter中使用数组作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!