在输出中没有最后一个逗号

时间:2012-10-30 16:51:29

标签: php csv

我有这段代码:

<?
$kate=mysql_query("select category_id from movies_cat where movie_id='$ids'");
   while($cat=mysql_fetch_array($kate)){
      $kate2=mysql_query("select name_cat from categories where id='$cat[category_id]'");
      $html = array();
        while($cat2=mysql_fetch_array($kate2)){
            $cat2['name_cat'].",";
    }
   }?>

我想输出没有最后逗号的类别!谢谢!

3 个答案:

答案 0 :(得分:1)

试试这个,在你的while循环之后,使用像这样的php trim函数:

while($cat2=mysql_fetch_array($kate2)){
            $cat2['name_cat'].",";
}
$cat2['name_cat'] = trim($cat2['name_cat'],",")

它将从字符串末尾删除,

答案 1 :(得分:0)

<?
$kate=mysql_query("select category_id from movies_cat where movie_id='$ids'");
while($cat=mysql_fetch_array($kate))
{
    $kate2=mysql_query("select name_cat from categories where id='$cat[category_id]'");
    $html = array();
    $first = true;
    while($cat2=mysql_fetch_array($kate2))
    {
        if ($first)
            $first = false;
        else
            print ",";

        print $cat2['name_cat'];
    }
}?>

答案 2 :(得分:0)

试试这个:

$display = "";
while($cat2=mysql_fetch_array($kate2)) {
    if ($display == "") {
        $display = $cat2['name_cat'];
    } else {
        $display .= ", " . $cat2['name_cat'];
    }
}

echo $display;