[英]How to match index array in form dropdown CodeIgniter with id in SQL?
<?php
$query= $this->db->query('SELECT state FROM states ORDER BY state= "New Jersey" desc, id asc');
$options = $query->result_array();
$options = array_column($options, 'state');
echo form_dropdown(array('name' =>'state' ), $options, set_value('states', isset($states->state) ? $states->state:'' ), lang('states_field_states'));
?>
New Jersey is set as default value in dropdown form and the index array is 0 but the ID in table for this states is 34 (my table: ID 1->50 for 50 states). 新泽西州以下拉列表的形式设置为默认值,索引数组为0,但此状态表中的ID为34(我的表:50个州的ID为1-> 50)。 How do I match the index array in dropdown form with id in table for all states?
如何在所有状态下将下拉列表中的索引数组与表中的ID匹配?
Make an associative array
with id
as key and state
as value in $options
. 在
$options
一个id
为key且state
为value的associative array
。 Like below. 像下面。
$this->db->select('id,state')
$this->db->from('states');
$states = $this->db->get()->result_array();
Make associative array
for $options
. 为
$options
建立associative array
。
foreach($states as $state)
{
$options[$state['id']] = $state['state'];
if($state['state'] = "New Jersey"){ //check id rather than name in case if edit
$selected = $state['id']
}
}
Then 然后
echo form_dropdown('state', $options, $selected);
will gives desire result. 将给欲望的结果。
Below is the code 下面是代码
$query= $this->db->query('SELECT id,state FROM states ORDER BY state= "New Jersey" desc, id asc');
$states = $query->result_array();
//$options = array_column($options, 'state');
// Add default state
$options[0] = "states";
foreach($states as $state){ // array with id as key and state name as value
$options[$state['id']] = trim($state['state']);
}
// get New Jersey state id
$default_select = array_search('New Jersey', $options);
echo form_dropdown('state', $options, $default_select); // to make the value selected.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.