PHP:用逗号分隔数组

5

我有这样一段代码,应该显示一个数组中的值列表,每个值后面跟着逗号和空格!但是,我不想在最后一个值后面加上逗号和空格。

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

这是我的代码:

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

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

2
你之前已经问过这个问题了。https://dev59.com/zVXTa4cB1Zd3GeqP012C - Nanne
不同的问题!我正在问如何去掉最后一个逗号! - Cameron
1
但答案仍然是 implode。例如,请查看 @rocket 的回答。 - Nanne
2个回答

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

让我想知道为什么像 PHP 这样的语言和像 WordPress 这样的框架都没有任何像样的库来执行最基本的操作。Rails -> array.join(", ") - Marek Maurizio
6
"它可以。implode(', ', $array)。" - gen_Eric

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接