摆脱最后一个逗号

时间:2012-05-02 17:56:39

标签: php string

  

可能重复:
  Removing last comma in PHP?
  Remove the last Comma from a string (PHP / Wordpress)

我的代码由于某种原因无效。我想要做的是从结果中删除最后一个逗号但它不起作用。这是代码

 <?php do { 
  $activity_user_first_name = $row_product_activity['user_first_name'];
  $activity_user_last_name = $row_product_activity['user_last_name'];
  $name = '<a href="">'.$activity_user_first_name.' '.$activity_user_last_name.'</a>, ';
  echo rtrim($name, ",");
 } while($row_product_activity = mysql_fetch_assoc($product_activity)) ?> like this

所以我想得到的结果就是这个

Steve Jobs, Bill Gates, Sergey Brin, Larry Page like this

相反,我得到了这个

Steve Jobs, Bill Gates, Sergey Brin, Larry Page, like this

所以我想在Larry Page或最后的任何其他名称之后删除该逗号。我尝试过玩很多其他选择,但没有按照我的意愿出现。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:6)

我认为更好的解决方案是首先构造不带尾随逗号的字符串。将每个名称的链接放入一个数组插槽中,然后回显一些内爆的结果。

<?php 
    $names=array();
    do { 
        $activity_user_first_name = $row_product_activity['user_first_name'];
        $activity_user_last_name = $row_product_activity['user_last_name'];
        $names[] = '<a href="#">'.$activity_user_first_name.' '.$activity_user_last_name.'</a>';
    } while($row_product_activity = mysql_fetch_assoc($product_activity));

    echo implode(', ', $names);    

?> Like This