开发者

Optimal way to generate list of PHP object properties with delimiter character, implode()?

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);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜