Houy Narun
Houy Narun

Reputation: 1715

How to Return Active Query Result as One-Dimensional Array in Codeigniter?

Every time, I query data from database table, it returns result as multi-dimensional array, so I have to do nested for-loop in view in order to get an actual data that I want. I don't want it to be like that because it is not necessary to a nested loop every time for my case. Is there any way that I can get only one dimensional array returned that points to actual data? Thanks.

Here's my model:

    public function get_contact_info($userid){
        $res = $this->db->get_where('contact_info',array('userid'=>$userid));
        return $res->result_array();
    }

Here's my controller:

   $userid = $this->session->userdata('userid');

   $this->load->model('User','user');
   $res = $this->user->get_contact_info($userid);

    var_dump($res);

Output:

   C:\wamp64\www\findjob.com\application\controllers\Job.php:64:
    array (size=2)
      0 => 
        array (size=6)
          'contact_id' => string '1' (length=1)
          'name' => string 'Jonh' (length=4)
          'title' => string 'Mr.' (length=3)
          'phone' => string '01932834784' (length=11)
          'email' => string '[email protected]' (length=14)
          'userid' => string '1' (length=1)
      1 => 
        array (size=6)
          'contact_id' => string '2' (length=1)
          'name' => string 'Smith' (length=5)
          'title' => string 'Mr.' (length=3)
          'phone' => string '0293893' (length=7)
          'email' => string '[email protected]' (length=15)
          'userid' => string '1' (length=1)

Upvotes: 1

Views: 1039

Answers (1)

Houy Narun
Houy Narun

Reputation: 1715

Since my model return result as an array of multiple rows and columns, there is no way to get data without looping. For instance, my loop as

    foreach($jobs as $key => $value){
      $value['column_name'];
    }

Because $value here is another array containing another key and value of itself, and it is the value that I need to get. Thus, from inside the loop, I used $value['column_name'] to access the value of each column that I need.

By this way, I can avoid using nested foreach loop, a loop through array $value. Thanks.

Upvotes: 1

Related Questions