关于php:WordPress-使用rtrim从输出中删除最后一个逗号

WordPress - remove last Comma from output with rtrim

我有以下代码,该代码是小部件的一部分,该小部件输出分类法"季节"的条款

分类术语在它们之间以空格和逗号输出,但最后也添加了逗号。

如何摆脱上一个逗号?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

global $post;  
$tags = get_the_terms( $post->ID, 'season' );

if( $tags ) : ?>

 <?php foreach( $tags as $tag ) :

  $tag_link = esc_url( get_term_link( $tag ) );
  $tag_output = '';
  $tag_output .= '';        
  $tag_output .= '<span class="tag__text">' . $tag->name . '</span>';
  $tag_output .=",";

  echo $tag_output;

  endforeach; ?>

 <?php endif;

echo $args['after_widget'];
}

我正尝试使用rtrim($tag_output,', ');,但我只是想不通将这个rtrim字符串放在哪里,以使其正常工作。

rtrim($tag_output,', ');应该在代码中的什么位置进行这项工作?


将数组映射到包含所需字符串的数组,然后使用implode()显示它可能会更容易。例如

1
2
3
4
5
6
7
8
9
10
11
12
13
if ($tags) {
    $tagOutput = array_map(function($tag) {
        return sprintf(
               '<span class="tag__text">%s</span>',
                esc_url( get_term_link( $tag ) ),
                $tag->name
        );
    }, $tags);

    echo implode(', ', $tagOutput);
}

echo $args['after_widget'];