get array of column values in codeigniter [closed] get array of column values in codeigniter [closed] codeigniter codeigniter

get array of column values in codeigniter [closed]


Each results row is itself an array so some looping is necessary! Why would you need to do it differently?

The most straightforward way to do what you want is:

// Modelfunction get_all_userid(){    $query = $this->db->get('table_name');    $array = array();    foreach($query->result() as $row)    {        $array[] = $row['user_id']; // add each user id to the array    }    return $array;}// Controllerfunction user_list(){    $data = $this->your_model->get_all_userid(); // get results array from model    $this->load->view('your_view', $data); // pass array to view}

Obviously you'll need to adjust the table/model names to match the ones you're using.


I did a research and found this:

Note: a 'magic' solution for that, for example: using a codeigniter custom function, I think doesn't exist in actual framework version. So, you need create a function in Model or in a Custom Helper.

Reference: Populate drop down list from database

Using your Model

// Controller$data['city_list'] = $this->City_model->get_dropdown_list();$this->load->view('my_view_file', $data); Model:// Model (or create a helper -- see below)function get_dropdown_list(){  $this->db->from('city');  $this->db->order_by('name');  $result = $this->db->get();  $return = array();  if($result->num_rows() > 0) {    foreach($result->result_array() as $row) {      $return[$row['id']] = $row['name'];    }  }  return $return;}// View<?php echo form_dropdown('city_id', $city_list, set_value('city_id', $city_id)); 

Using a Helper

if ( ! function_exists('drop_down')){    function drop_down($name, $match, $data)    {        $form = '<select name="'.$name.'"> ' ."\n";        foreach($data as $key => $value)        {                                            $selected = ($match == $key) ? 'selected="selected"' : NULL ;            $form .= '<option value="'. $key .'" '. $selected .'>'.$value.'' . "\n";        }                   $form .= '</select>' . "\n";        return $form;    }} In the viewecho drop_down('mylist', 3, $data);