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

前端 未结 14 1418
醉话见心
醉话见心 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:01

    First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:

    ob_start();
    foreach($results as $result)
    {
       echo $result->name.',';
    }
    $output = ob_get_clean();
    
    echo rtrim($output, ',');
    

    The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

提交回复
热议问题