I have an array of stdClass
objects and I want to build a comma separated list using one specific field of all those stdClass
objects. My array looks like this:
$obj1 = stdClass Object ( [foo] => 4 [bar] => 8 [foo-bar] => 15 );
$obj2 = stdClass Object ( [foo] => 16 [bar] => 23 [foo-bar] => 42 );
$obj3 = stdClass Object ( [foo] => 76 [bar] => 79 [foo-bar] => 83 );
$a = array(1=>$obj1 , 2=>$obj2 , 3=>$obj3);
And I want to implode on foo
of all the stdClass
objects in that array to create a comma separated list. So the desired result is:
4,16,76
Is there any way to do this with implode (or some other mystery function) without having to put this array of objects through a loop?
With PHP 7.0+ you can use
array_column
for this.You can actually set
__toString()
on the class as suggested by Ray, but you don't need to iterate through thearray
first.implode()
will directly call the__toString()
function of the objects (which also works with associative arrays, btw).If it's a 1-level object, this worked for me.
Could include a by-type multi-level process, but I didn't need that yet. Hope this helps.
Handy for converting MySQL object back to array.
I guess the easiest way would be to create an ID indexed array and then call implode on array_keys:
No, the best you can do is iterate through, call tostring() on the object and put the results in a new array to call implode on.