2011-12-28 56 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