2017-06-09 26 views
0
<?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')); 
?> 

enter image description here enter image description here
新澤西被設定爲下拉形式默認值和索引數組是0,但是在表中的ID爲這個狀態是34(我的表:ID 1-> 50 50種狀態)。如何將下拉表單中的索引數組與所有狀態的表中的id匹配?如何匹配索引數組中的表單下拉CodeIgniter與SQL中的ID?

+0

不明白您的查詢,請詳細說明。 –

+0

如果狀態等於慾望狀態設置,那麼留下空白它是什麼? –

+0

刪除這行代碼$ options = array_column($ options,'state'); –

回答

0

以作爲id作爲關鍵字,state作爲$options的值。如下所示。

$this->db->select('id,state') 
$this->db->from('states'); 

$states = $this->db->get()->result_array(); 

使associative array$options

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); 

的意志帶給渴望的結果。

+0

以及如何在下拉列表中顯示新澤西州作爲默認值? – jenii

+0

需要通過第三個參數進行默認選擇。 –

+0

嘗試編輯答案。 –

0

下面是代碼

$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. 
+0

錯誤:未定義的索引:$ options [$ state ['id']] = $ state ['state']; – jenii

+0

檢查編輯的答案。 –

+0

它工作!但狀態標籤消失: echo form_dropdown(array('name'=>'state'),$ options,$ default_select,set_value('states',isset($ states-> state)$ states-> state: ''),lang('states_field_states')); – jenii

相關問題