Search code examples
phparrayscodeigniterimplode

Collect and implode column values from multiple query result sets in a CodeIgniter query


I have an array of the following format:

$var = Array
     ( 
     [0] => Array
         (
        [name] => Harry
          )

      [1] => Array
         (
        [name] => Wayne
          )

      )
 Array
     (
     [0] => Array
         (
        [name] => Wayne
         )

I want to implode this array such that i get it in the format:

 Harry,Wayne
 Wayne

From What I have Tried I am getting it in format:

Harry,Wayne
Harry,Wayne,Wayne

What I have Tried (Not important as its wrong)

foreach($var as $a){
 foreach($a as $b){
 }$c[] = $b
   }
 $imp = implode(',',$c);

$var is fetched from database using fetch_array.

    $this->db->select('name');
    $this->db->where('id', $Id);
    $this->db->from('info');
    $row = $this->db->get();
    $var = $row->result_array();

where $Id is array containing certain user ids.


Solution

  • Try this.

    foreach($var as $a){
      $m = '';
      $delim = '';
      foreach($a as $k){
         $m .= $delim . $k['name'];
         $delim = ',';
      }
    
      $c[] = $m;
    }
    
    foreach($c as $d){
      echo $d;
    }