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

查看:114
本文介绍了如何从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天全站免登陆