Home » Php » php – get array of column values in codeigniter

php – get array of column values in codeigniter

Posted by: admin July 12, 2020 Leave a comment

Questions:

i have a table with this structure:

ID int(11)

user_id int(11)

notification_event_id int(11)

how can i get an array that contains all values of user_id column :

EX:

Array([0]=> 1,[1]=>2,[2]=>3,[3]=>4,[4]=>5,[5]=>6);

and without looping on the result_array() value and moving the user_ids to a new integers array

is that possible?

How to&Answers:

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:

// Model
function 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;
}

// Controller
function 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.

Answer:

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 view

echo drop_down('mylist', 3, $data);