How to use implode a column from an array of stdCl

2020-07-01 06:31发布

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?

9条回答
看我几分像从前
2楼-- · 2020-07-01 07:04

A very neat solution for this is the array_reduce() function, that reduces an array to a single value:

$str = array_reduce($a, function($v, $w) {
    if ($v) $v .= ',';
    return $v . $w->foo;
});
查看更多
来,给爷笑一个
3楼-- · 2020-07-01 07:07

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);
查看更多
Animai°情兽
4楼-- · 2020-07-01 07:08

This is actually the best way I've found, it doesn't seem to be answered here properly as the array of objects should be able to handle dynamic size.

$str = implode(',', array_map(function($x) { return $x->foo; }, $a));

This also seems to be the cleanest solution I've seen.

查看更多
登录 后发表回答