How do I create a comma-separated list from an array in PHP?(如何从 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 中的数组创建逗号分隔的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 PHP 中的数组创建逗号分隔的列表?


- Mod使用GET变量将子域重写为PHP 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01