2009-07-21 119 views
0

這可能是真的很明顯,簡單的 - 但它是不是我與我的基礎知識:)分組結果

我有兩個表:

table_items 
----------- 
item_id ¦ item_name ¦ item_describtion ¦ more item stuff..... 

table_subitems 
----------------- 
subitem_id ¦ item_id ¦ subitem_name ¦ More subitem stuff 

每個項目都具有零到幾乎無限的子項目,並通過字段item_id相關。

我想打印出按項目分組的子項目。

我目前正在與它選擇子項目,其中table_items.item_id = table_subitems.item_id然後將其顯示while循環,這是儘可能去細查詢這樣做,我得到的是這樣的:

Item One 
======== 
Subitem 0ne 

Item One 
======== 
Subitem two 

Item One 
======== 
Subitem three 

Item Two 
======== 
Subitem one 

Item Three 
========== 
Subitem one 

Item Three 
========== 

Subitem two 

但我想要

ITEM ONE 
-------- 
Subitem one 
Subitem two 
Subitem three 

ITEM TWO 
-------- 
Subitem one 

ITEM THREE 
---------- 
Subitem one 
Subitem two 

我該怎麼做?它是查詢的功能還是我顯示結果的功能?我對PHP的知識在增長,但仍然有限,我以程序化的方式來做這件事(即它不是OOP,我試圖把握但沒有完全),所以跟我說話就像我一樣笨。

回答

1

使用包含最後航向的變量,然後打印當前只有當它不同於過去的標題:

$last = null; 
while (/* … */) { 
    if ($row['item_id'] != $last) { 
     echo '<hx>'.$row['item_name'].'</hx>'; 
     $last = $row['item_id']; 
    } 
    echo $row['subitem_name']; 
} 
+0

謝謝,工作完美! – Katherine 2009-07-21 12:28:47

1

你可以做這樣的事情,它每次更改時間打印新物品名稱:

$last_item_id = null; 

foreach ($rows as $row) { 
    if ($row->item_id != $last_item_id) { 
     echo "<h2>{$row->item_name}</h2>\n"; 
     $last_item_id = $row->item_id; 
    } 

    echo "{$row->subitem_name}<br />\n"; 
}