データを取得したいテーブルが2つあります。最初のテーブルはカテゴリと呼ばれ、次のように構成されています。
---------------------------------
id | name | parent |
--------------------------------- |
1 | Desktop Courses | 0 |
2 | Adobe | 1 |
3 | CS6 | 2 |
4 | IT Courses | 0 |
5 | Microsoft | 4 |
6 | Server 2008 | 5 |
次のコードを使用して、データをリストとして表示しています。
<?php
//Connect to mysql server
$cn = mysql_pconnect("server", "username", "password");
mysql_select_db("database");
$rs = mysql_query("SELECT id, parent, name FROM course_categories", $cn);
$childrenTree = array();
$categoryNames = array();
while($row = mysql_fetch_array($rs)){
list($id, $parent, $name) = $row;
$categoryNames[(string)$id] = $name;
$parent = (string)$parent;
if(!array_key_exists($parent, $childrenTree))
$childrenTree[$parent] = array();
$childrenTree[$parent][] = (string)$id;
}
function renderTree($parentid = "0"){
global $categoryNames;
global $childrenTree;
if($parentid != "0") echo "<li> ", $categoryNames[$parentid], "\n";
$children = $childrenTree[$parentid];
if(count($children) > 0){ //If node has children
echo "<ul>\n";
foreach($children as $child)
renderTree($child);
echo "</ul>\n";
}
if($parentid != "0") echo "</li>\n";
}
renderTree();
?>
したがって、これは明らかに次のようにデータをプルします。
Desktop Courses
Adobe
CS6
IT Courses
Microsoft
Server 2008
これで、次のように構成されたコースを表示するテーブルも作成されました。
---------------------------------------------------
id | categoryid | course |
---------------------------------------------------|
1 | 3 | Photoshop CS6 |
2 | 6 | Active Directory |
ここで、コースのデータをカテゴリリストにマージしたいのですが、次のように表示されるようにする方法がわかりません。
Desktop Courses
Adobe
CS6
Photoshop CS6
IT Courses
Microsoft
Server 2008
Active Directory
どんな助けでも大歓迎です。