Mariano
Mariano

Reputation: 221

Serialize an object array

I have this object array:

array (size=[...])
  0 => 
    object(stdClass)[2382]
      public 'id' => string '1' (length=1)
  1 => 
    object(stdClass)[2383]
      public 'id' => string '2' (length=1)
  [...]

How can I serialize it to 1, 2, [...]?
I tried with implode(', ', $array) but as it is an object it returns CATCHABLE FATAL ERROR: OBJECT OF CLASS STDCLASS COULD NOT BE CONVERTED TO STRING

Upvotes: 0

Views: 93

Answers (1)

Jon
Jon

Reputation: 437336

What you want to do is not quite serialize things (this term usually refers to converting object instances to a binary form) but rather map each element (object) to its id and then concatenate these ids.

You can do that with:

$ids = array_map(function($obj) { return $obj->id; }, $array);
echo implode(', ', $ids);

Upvotes: 1

Related Questions