我正在和PHP打架。我的代码输出正确,但最后留下了一个不需要的逗号。有没有办法得到(或显示)最后一个逗号?任何提示都表示赞赏。
<?php echo mtbxr_val('dog_name'); ?>
is
<?php
$terms = get_the_terms( $post->ID , 'behaviour_options' );
foreach ( $terms as $term ) {
echo mb_strtolower($term->name);
echo ", ";
}
?>
答案 0 :(得分:3)
通常我会存储在数组中并使用implode()
:
foreach ( $terms as $term ) {
$output[] = mb_strtolower($term->name);
}
echo implode(', ', $output);
答案 1 :(得分:0)
这将是一种更容易的方法
<?php
$terms = get_the_terms( $post->ID , 'behaviour_options' );
$out = array();
foreach ( $terms as &$term ) {
$out[] = mb_strtolower($term->name);
}
echo implode(", ",$out);
?>
答案 2 :(得分:0)
我喜欢使用数组来收集值,然后使用join()进行回显。例如:
<?php
$terms = get_the_terms( $post->ID , 'behaviour_options' );
$names = array();
foreach ( $terms as $term ) {
$names[] = mb_strtolower($term->name);
}
echo join(', ', $names);
?>
答案 3 :(得分:0)
除了内爆之外,您还可以使用计数器:
<?php
$terms = get_the_terms( $post->ID , 'behaviour_options' );
$termCount = count($terms);
foreach ( $terms as $term ) {
echo mb_strtolower($term->name);
if (--$termCount) echo ", ";
}
?>