MDS
MDS

Reputation: 507

String from Multidimensional array

I have an array similar to this but could be more or less pet names:

  Array ( [0] => Array ( [pet_name] => Bella ) [1] => Array ( [pet_name] => Zoey ) [2] => Array ( [pet_name] => Pooky ) ) 

And I'm trying to get a string like this:

Bella,Zoey,Pooky

I've tried to implode the array but I get a php error notice. Ive tried:

call_user_func_array('array_merge',$array);

But it only returns the first sub array.

How do I go about iterating through this array and creating a string from the pet names? I'm still learning how to work with complex arrays.

Upvotes: 0

Views: 37

Answers (1)

scrowler
scrowler

Reputation: 24405

You need to select the correct array key before imploding:

<?php
$pet_names = array();
foreach($array as $current) {

    $pet_names[] = $current['pet_name'];

}

echo implode(',', $pet_names);

// Bella,Zoey,Pooky

?>

Upvotes: 1

Related Questions