从对象数组的单个列创建逗号分隔的字符串 [英] Create a comma-separated string from a single column of an array of objects

查看:73
本文介绍了从对象数组的单个列创建逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个foreach循环从数据库中回显一些值,如果需要的话,我需要从最后一个循环中去除最后一个逗号。

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 below

foreach($results as $result){
  echo $result->name.',';
}

回显了

result,result,result,result,

我只需要杀死那个讨厌的最后一个逗号即可。

I just need to kill that pesky last comma.

推荐答案

首先使用输出缓冲获取所有输出。然后,修剪逗号并显示它。因此,请按照以下步骤操作:

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

如果内部循环很大,则输出缓冲方法会有所帮助(为了简洁起见,OP在此处发布) ),那么使用OB更容易,而无需更改循环的内部结构。

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.

这篇关于从对象数组的单个列创建逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆