PHP:用逗号分隔数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5407381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:17:47  来源:igfitidea点击:

PHP: Separate array with commas

phparrays

提问by Cameron

I have this code that should display a list of values from an array followed by a comma and space! However I don't want the last one to have a comma and space after it.

我有这段代码应该显示一个数组中的值列表,后跟一个逗号和空格!但是我不希望最后一个后面有逗号和空格。

So for example I want tag1, tag2, tag3instead of tag1, tag2, tag3,

所以例如我想要tag1, tag2, tag3而不是tag1, tag2, tag3,

This is my code:

这是我的代码:

<?php $terms = get_the_terms( $the_post->ID, 'posts_tags' );
                                foreach ( $terms as $term ) {

                                    echo $term->name;echo ", ";
                                } ?>

回答by Rocket Hazmat

$output = array();
foreach($terms as $term){
  $output[] = $term->name;
}
echo implode(', ', $output);

回答by Tobias

It′s an build in php feature called implode -> http://php.net/manual/function.implode.php

它是一个内置的 php 功能,称为 implode -> http://php.net/manual/function.implode.php