在类别上显示没有最后一个逗号

时间:2012-10-31 17:08:21

标签: php mysql show

我有这段代码:

<?
$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]'");
        while($cat2=mysql_fetch_array($kate2)){
            print $cat2['name_cat'];
    }

   }

?>

现在显示以下类别:ActionsComedyMystery,我想显示动作,喜剧,神秘(最后没有逗号)

3 个答案:

答案 0 :(得分:0)

将类别插入数组并使用implode()函数连接它们。

$result = implode(",", $items);

用你的例子:

<?
$items = Array();

$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]'");
  while($cat2=mysql_fetch_array($kate2)){
    $items[] = $cat2['name_cat'];
  }
}

echo implode(",", $items);
?>

编辑:使用Mysqli和加入:

<?
$db = @new mysqli( 'host', 'user', 'pass', 'database' );

$items = Array();

$kate = $db->query("select movies_cat.category_id, categories.name_cat from movies_cat, categories where movies_cat.category_id = categories.name_cat AND WHERE movie_id='$ids'");
while($cat = $kate->fetch_array($kate)){
    $items[] = $kate['name_cat'];
}

echo implode(",", $items);
?>

答案 1 :(得分:0)

您可以将类别保存到var然后在结束时回显该变量,省略最后一个字符,如下所示:

$out = '';
$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]'");
        while($cat2=mysql_fetch_array($kate2)){
            $out .= $cat2['name_cat'] . ',';
    }

   }

echo substr($out,0, -1);

答案 2 :(得分:0)

首先定义变量。使用PDO而不是mysql_query。尝试优化你的逻辑。

$category = ""

现在,

$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]'");
    while($cat2=mysql_fetch_array($kate2)){
        $category .= $cat2['name_cat'].",";
   }

 }

echo substr_replace($category ,"",-1);