Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get array of column values in codeigniter [closed]

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?

like image 675
Majed DH Avatar asked Oct 14 '13 13:10

Majed DH


2 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.

like image 176
TKC Avatar answered Nov 10 '22 06:11

TKC


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); 
like image 23
Patrick Maciel Avatar answered Nov 10 '22 07:11

Patrick Maciel