如何从 PHP 中的数组创建逗号分隔的列表? [英] How do I create a comma-separated list from an array in PHP?

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

问题描述

我知道如何使用 foreach 循环遍历数组的项目并附加一个逗号,但必须去掉最后一个逗号总是很痛苦.有没有一种简单的 PHP 方法可以做到这一点?

I know how to loop through items of an array using foreach and append a comma, but it's always a pain having to take off the final comma. Is there an easy PHP way of doing it?

$fruit = array('apple', 'banana', 'pear', 'grape');

最终我想要

$result = "apple, banana, pear, grape"

推荐答案

你想使用 内爆为此.

即:$commaList = implode(', ', $fruit);

有一种方法可以在不带尾随的情况下附加逗号.如果您必须同时进行一些其他操作,您会想要这样做.例如,也许您想引用每个水果,然后用逗号分隔它们:

There is a way to append commas without having a trailing one. You'd want to do this if you have to do some other manipulation at the same time. For example, maybe you want to quote each fruit and then separate them all by commas:

$prefix = $fruitList = '';
foreach ($fruits as $fruit)
{
    $fruitList .= $prefix . '"' . $fruit . '"';
    $prefix = ', ';
}

另外,如果你只是按照正常"的方式在每个项目之后附加一个逗号(就像你之前所做的那样),并且你需要修剪最后一个,只需执行 $list =rtrim($list, ', ').我看到很多人在这种情况下不必要地使用 substr.

Also, if you just do it the "normal" way of appending a comma after each item (like it sounds you were doing before), and you need to trim the last one off, just do $list = rtrim($list, ', '). I see a lot of people unnecessarily mucking around with substr in this situation.

这篇关于如何从 PHP 中的数组创建逗号分隔的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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