2011-12-28 59 views
2

我有一些数据在数据库中,它的输出与ORDER BY category,我想知道如何只显示一次类别?mysql中的类别显示一次

$SQL = mysql_query("SELECT id,name,category FROM table ORDER BY category,id"); 

所以我的脚本遍历整个表并按类别名排序所有项目。

我希望能够以显示类别名称,一旦如此,则其余值可以落在该类别内

我现在有这样的事情

while($r = mysql_fetch_array($SQL){ 
    $name = $r['name']; 
    $category = $r['category']; 

    echo $category; //I want to be able to echo this once 
    echo $name; // this will be echoed many times depending on the category this falls into 
} 
+0

请看[PDO](http://www.php.net/pdo)。 – 2011-12-28 18:47:17

+1

@PhpMyCoder PDO与OP的问题有什么关系? – PeeHaa 2011-12-28 18:50:41

+0

@PeeHaa我们不应该鼓励在过时的'mysql_ *'系列函数中使用PDO吗? – 2011-12-28 18:56:47

回答

4
$category = null; 
while($r = mysql_fetch_array($SQL){ 
    $name = $r['name']; 

    if ($category != $r['category']) { 
     $category = $r['category']; 

     echo $category; //I want to be able to echo this once 
    } 
    echo $name; // this will be echoed many times depending on the category this falls into 
} 
3

这样做:

$prev_category = ""; 
while($r = mysql_fetch_array($SQL){ 
    $name = $r['name']; 
    $category = $r['category']; 

    if($prev_category != $category) 
     echo $category; 
    echo $name; 
    $prev_category = $category; 
} 

因此,只有在更改后才会打印新类别

+2

怀抱起来,谢谢,增加了初始化。但这不是一个错误,只是警告。这是PHP =) – SlavaNov 2011-12-28 18:47:58

+0

谢谢slava,但@PeeHaa有一个工作片段,它对我没有任何警告很有效:) – hellomello 2011-12-28 18:49:28

+0

@Slava是啊那就是我讨厌PHP的原因。不是,但你知道我的意思:) – PeeHaa 2011-12-28 18:52:40