Comma separated list from objects. A better way?

Anyone know a better way of doing this:

$a = new stdClass;
$a->id = 1 ;
$b = new stdClass;
$b->id = 2 ;

$arr = array( $a, $b );

// from that generate string "(1,2)"

$html = "(" ;
foreach( $arr as $ar )
$html .= $ar->id . ',';

$out = rtrim(  $html , ',' ) . ')';
var_dump( $out );
// (1,2)

ie create a comma-separated string from an array of object properies (a PDO result set - returned using the object notation PDO::FETCH_OBJ)

Seems mucky.

I’m assuming here the following:

  1. you’re wanting generalized code that can handle as many result returns as desired,
  2. that you -have- to use objects (rather than PDOStatement::fetch() ).
  3. that you have a need for those objects prior to this code, and therefore have prefetched them rather than doing it inside the loop.
  4. that your PDOStatement is returning an object with a field name ‘id’

If any of those are false, then the code will change.

Since each object is returned as standardized object…

$out = "(";
foreach($arr AS $o) {
  $out .= $o->id.",";
}
$out = substr($out,0,-1).")";
echo $out;

Is about as simple as you can make that block.
Why, though, are you not simply compiling $out (or $html, or whatever you want to call your variable), while filling the $arr array with your fetch_object calls?

How about:


$ids = array_map(function($row){ return $row->id; }, $arr);
echo '(' . implode(',', $ids) . ')';

Or:


$ids = array();
foreach ($arr as $row) {
    $ids[] = $row->id;
}
echo '(' . implode(',', $ids) . ')';

function doit($row){ return $row->id; }

$ids = array_map( "doit", $arr );

echo '(' . implode(',', $ids) . ')';

Doing it this way works, was yours an example of PHP5.3 code “closures”?

@starlion, thanks, getting the result as an array then imploding seems more understandable when I read it.

Agreed though, the best way would be to get PDO arrays from the outset.

Thanks for your comments both.

Yes, it uses the anonymous function syntax introduced in PHP 5.3.0. I usually put a quick note saying so, since many aren’t yet lucky enough to use 5.3 all of the time, but forgot to do so. (:

Ah, Lambda functions I should have said.

http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html

All very jQuery-like.