如何从 PHP 中的数组创建逗号分隔的列表?

2022-01-31 00:00:00 arrays 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.

相关文章