duanjiao5543 2010-03-28 01:59
浏览 77
已采纳

使用分隔符,implode()生成PHP对象属性列表的最佳方法?

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);
  • 写回答

2条回答 默认 最新

  • douhuan1901 2010-03-28 02:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?