codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?
2 Answers
Let's say you want a dropdown of items, using result_array():
$query = $this->db->query("SELECT id, item_name FROM items");
$options = array();
foreach ($query->result_array() as $row){
$options[$row['id']] = $row['item_name'];
}
echo form_dropdown('my_items_dropdown', $options, '1');
3 Comments
John Corry
check out Jamie rumbelows my_model class, it has a method for getting an associative array from a table.
prograhammer
I think the idea is that you generate and return the $options in your model. So the above code would reside in your model with: return $options. Then in your controller you can then do something like: $data['item_options'] = $this->load->model('items_model'); Then in your controller also pass this to your view: $this->load->view('my-view', $data); Then in your view: <?= form_dropdown('my_items_dropdown',$item_options,'1'); ?>
I have extended the class DB_result.php in system/database with this new function
public function dropdown_array($id_field = FALSE, $list_field = FALSE)
{
$result = array();
if ($id_field === FALSE || $list_field === FALSE) return $result;
$array = $this->result_array();
foreach ($array as $value) {
$result[$value[$id_field]] = $value[$list_field];
}
return $result;
}
Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:
$customers = $this->db->get('customers');
$result = $customers->dropdown_array('id', 'name');
return $result;