0

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.

2
  • Seems like both are different arrays. Commented Jan 2, 2013 at 5:26
  • What about the second array block? it is a different array right? or what? Commented Jan 2, 2013 at 5:29

4 Answers 4

1
foreach($var as $a)
{
    unset($temp);
    foreach($a as $b)
    {
        $temp[] = $b['name'];
    }
    $c[] = implode(",", $temp);
}

// output all the names
foreach ($c as $csvNames)
{
    echo $csvNames;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

1 Comment

@Venu, it is always better to have your own algo rather than using built in functions. That will not only increase your skills but also it increase your finding solutions skills
0

Please ignore those hard-coded loops. There is a recursive function for it.

array_walk_recursive($var, create_function('$val, $key', 'array_push($obj, $val);'), &$output);
echo implode(",",$output);

Comments

0

Your question says

where $Id is array containing certain user ids.

Well, CodeIgniter's query builder method where() is not designed to receive an array in the way that you are scripting it. I can only assume that you are making iterated trips to the database -- that us both bad practice and avoidable.

To return a flat array of column values from your database query, use where_in() then array_column() on the result set.

The imploding step is likely to be a job for the presentation layer, so defer that process for the view layer.

return array_column(
    $this->db
        ->where_in('id', $ids)
        ->get('name')
        ->result(),
    'name'
);

This will return a flat array of all names from qualifying rows via a single trip to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.