views:

237

answers:

2

I am trying to find out if there is a more optimal way for creating a list of an object's sub object's properties. (Apologies for the crude wording, I am not really much of an OO expert)

I have an object "event" that has a collection of "artists", each artist having an "artist_name". On my HTML output, I want a plain list of artist names delimited by a comma.

PHP's implode() seems to be the best way to create a comma delimited list of values. I am currently iterating through the object and push values in a temporary array "artistlist" so I can use implode().

That is the shortest I could come up with. Is there a way to do this more elegant?

$artistlist = array();
foreach ($event->artists as $artist)
{
    $artistlist[] = $artist->artist_name;
}
echo implode(', ', $artistlist);
A: 

Besides just creating the string yourself and appending the comma after each artist (which means you need to also deal with the final comma appropriately), you have the most concise way to do this already.

Marc W
exactly, the last comma was what I was trying to avoid
Kris
+1  A: 

There isn't really a faster way. With PHP 5.3, you can use array_map and an anonymous function:

implode(', ', array_map(function ($artist) { 
        return $artist->artist_name;
    } , $event->artists));

Which is more elegant, I leave up to you.

outis
in <5.3 you can still do this, but you use create_function to create the anonymous function.
intuited
interesting, didn't think of that. Me like. :)
Kris
@intuited: `create_function` is just so inelegant. I usually never bother with it.
outis