PHP:用','作为分隔符将数组元素连接成字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1387142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Concatenate array element into string with ',' as the separator
提问by Graviton
Is there a quick way ( existing method) Concatenate array element into string with ',' as the separator? Specifically I am looking for a single line of method replacing the following routine:
有没有一种快速的方法(现有方法)将数组元素连接成以“,”为分隔符的字符串?具体来说,我正在寻找一行替换以下例程的方法:
//given ('a','b','c'), it will return 'a,b,c'
private static function ConstructArrayConcantenate($groupViewID)
{
$groupIDStr='';
foreach ($groupViewID as $key=>$value) {
$groupIDStr=$groupIDStr.$value;
if($key!=count($groupViewID)-1)
$groupIDStr=$groupIDStr.',';
}
return $groupIDStr;
}
回答by Artelius
回答by carl
回答by karim79
$arr = array('a','b','c');
$str = join(',',$arr);
join is an alias for implode, however I prefer it as it makes more sense to those from a Java or Perl background (and others).
join 是 implode 的别名,但我更喜欢它,因为它对那些有 Java 或 Perl 背景(和其他人)的人更有意义。
回答by Tareq
implode() function is the best way to do this. Additionally for the shake of related topic, you can use explode() function for making an array from a text like the following:
implode() 函数是最好的方法。此外,对于相关主题的震动,您可以使用explode() 函数从文本中创建数组,如下所示:
$text = '18:09:00'; $t_array = explode(':', $text);
$text = '18:09:00'; $t_array = expand(':', $text);
回答by gxthegreat
You can use implode() even with empty delimeter: implode(' ', $value);pretty convenient.
即使使用空分隔符,您也可以使用 implode():implode(' ', $value);非常方便。

