簡體   English   中英

如何在SQL中使用ID將表單下拉CodeIgniter中的索引數組與ID匹配?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM