Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use implode a column from an array of stdClass objects?

Tags:

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?

like image 394
ubiquibacon Avatar asked May 31 '12 12:05

ubiquibacon


2 Answers

You could use array_map() and implode()...

$a = array_map(function($obj) { return $obj->foo; },                 array(1=>$obj1 , 2=>$obj2 , 3=>$obj3));  $a = implode(", ", $a); 
like image 140
alex Avatar answered Sep 18 '22 00:09

alex


With PHP 7.0+ you can use array_column for this.

echo implode(',', array_column($a, 'foo')); 
like image 22
Don't Panic Avatar answered Sep 21 '22 00:09

Don't Panic