如何删除Wordpress php foreach输出的最后一个逗号



我已经尝试了一些trim之类的东西,但都不起作用。

也许我犯了一个错误,你可以帮我吗?当前代码如下所示:

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
$output = '';
foreach ($terms as $term) {
$output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a>, ';
}
};
echo $output;

尝试放入substr_replace($term->name,"",-1),查看文档以获取更多信息,这应该会从最后一个字符串中删除逗号。

只需添加一个计数器来检查数组的最后一项

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
$output = '';
$i = 0;
foreach ($terms as $term) {
$output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a> ';
$output .= ($i == count($terms) - 1) ? '' : ',';
$i++;
}
};
echo $output;

最新更新