[英]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'));
?>
新澤西州以下拉列表的形式設置為默認值,索引數組為0,但此狀態表中的ID為34(我的表:50個州的ID為1-> 50)。 如何在所有狀態下將下拉列表中的索引數組與表中的ID匹配?
在$options
一個id
為key且state
為value的associative array
。 像下面。
$this->db->select('id,state')
$this->db->from('states');
$states = $this->db->get()->result_array();
為$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']
}
}
然后
echo form_dropdown('state', $options, $selected);
將給欲望的結果。
下面是代碼
$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.