Search code examples
phparraysstdclass

php, how to convert an array containing stdClass Object into comma separated list


when I print_r $output I get the following

Array ( [0] => stdClass Object ( [id] => foo ) [1] => stdClass Object ( [id] => bar ) [2] => stdClass Object ( [id] => foobar ))

Im trying to do something which I though would be simple and convert the $output into

foo, bar, foobar 

I have tried using for each statements such as below

foreach($array as $row){
   $new_array[$row['nid']] = $row['nid'];
}
print_r($new_array);

but I just get invalid php.

I have tried ausing arraywalk and other examples here but not getting anything to work.

So how do I convert the following Array into a simple list of IDs? Thanks for any help


Solution

  • Except for the comma separated list, what you have should work in theory, but the code doesn't at all match your array. You state $object not $array and the property is id not nid.

    However, just extract the id column and implode. If you have PHP 7:

    $list = implode(', ', array_column($output, 'id'));
    

    For older versions:

    $list = implode(', ', array_map(function($v) { return $v->id; }, $output));