Skip to content
Advertisement

Convert array objects to string and separate the values

I have the following result

Array ( 
      [0] => stdClass Object ( [name] => Identification ) 
      [1] => stdClass Object ( [name] => Assay ) 
      [2] => stdClass Object ( [name] => pH(Acidity/Alkalinity)) 
      [3] => stdClass Object ( [name] => Sterility )
    ) 

What i want is to separate the object array values using a comma and return as a string, so as to have this result:

 Identification, Assay, ph(Acid/Alkalinity), Sterility

I have tried the following

$data=(array)$result;
$answer=implode(",",$data);

This return :

Message: Object of class stdClass could not be converted to string

How best can this be achieved?

Advertisement

Answer

You are missing the fact that you are dealing with an array of objects.

Looks like you can achieve that by doing:

$output = array_map(function ($object) { return $object->name; }, $input);
echo implode(', ', $output);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement