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

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

    In modern PHP, array_column() wil allow you to isolate a column of data within an array of objects.

    Code: (Demo)

    $results = [
        (object)['name' => 'A'],
        (object)['name' => 'B'],
        (object)['name' => 'C']
    ];
    
    echo implode(',', array_column($results, 'name'));
    

    Output:

    A,B,C
    

    That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.

提交回复
热议问题