简体   繁体   中英

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). How do I match the index array in dropdown form with id in table for all states?

Make an associative array with id as key and state as value in $options . Like below.

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

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

Make associative array for $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']
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM