Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
alphy Avatar asked May 12 '13 08:05

alphy


People also ask

How do you turn an array of objects into a string?

To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.

How do you separate data in an array?

The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.

How do I convert an array of numbers to strings?

To convert an array of numbers to an array of strings, call the map() method on the array, and on each iteration, convert the number to a string. The map method will return a new array containing only strings.

How do you split an array into an object?

Example 1: Split Array Using slice() The for loop iterates through the elements of an array. During each iteration, the value of i is increased by chunk value (here 2). The slice() method extracts elements from an array where: The first argument specifies the starting index.


1 Answers

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);
like image 60
magnetik Avatar answered Oct 17 '22 05:10

magnetik