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

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

问题描述

我正在使用 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.

我的循环很简单,如下

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天全站免登陆