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

   }

?>

现在在此显示类别:ActionsComedyMystery,我想显示 Actions,Comedy,Mystery(末尾没有逗号)

4

3 回答 3

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);
?>
于 2012-10-31T17:10:40.607 回答
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);
于 2012-10-31T17:11:26.987 回答
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);
于 2012-10-31T17:13:56.850 回答