如果不等于WordPress PHP但是如果大于

时间:2013-11-19 01:27:14

标签: php wordpress

我有一个WordPress网站,我试图使用PHP动态创建逗号分隔的值列表。但是我的所有列表在最后都有逗号,但是我似乎无法解决如何删除它。

我目前的代码是;

$tcount=count($terms);
foreach($terms as $term){
    echo $term->name;
    if($tcount>1){
        echo ', ';
    }
}

最后有一个逗号,它应该只是空白。我尝试了以下代码,但它没有用;

$tcount=count($terms);
foreach($terms as $term){
    echo $term->name;
    if(!$tcount==$tcount && $tcount>1){
        echo ', ';
    }
}

有谁知道我做错了什么?

3 个答案:

答案 0 :(得分:2)

修剪最后一个逗号:

$result = "";

$tcount=count($terms);
foreach($terms as $term) {
  // save output in temporary variable...
  $result .= $term->name;
  $result .= ', ';
}
echo substr($result, 0, -2);  // delete last two characters (", ")

答案 1 :(得分:0)

您使用rtrim()

像这样:

rtrim($string, ',');

Example

答案 2 :(得分:0)

你应该尝试使用php的内置功能。<​​/ p>

它将最小化代码和精确的方式

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

感谢