从foreach循环中剥离最后一个逗号 [英] Stripping last comma from a foreach loop

查看:112
本文介绍了从foreach循环中剥离最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im 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.

这篇关于从foreach循环中剥离最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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