Create a comma-separated string from a single column of an array of objects

前端 未结 14 1412
醉话见心
醉话见心 2020-11-30 07:36

I\'m using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.

My loop is just simple, as

14条回答
  •  心在旅途
    2020-11-30 08:04

    This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.

    $i = 0;
    $string = '';
    
    foreach($array as $item){
        $string .= ($i++ ? ',' : '').$item;
    }
    

提交回复
热议问题