我想優化一個多對多的設計,它將返回一個像結構樹。數據是這樣的:PHP mySQL結構輸出樹
頁表:ID,標題,副標題,類 網頁連接器表:ID,PAGE_ID,PARENT_ID,部分
如果部分= X,對於具有孩子每個父母其中一節= X標記應該是這樣的:
--- start parent 1 ---
-- if first parent echo *
<>* parent page id | parent title<>
--- parent 1 children ---
<>child page id | child title<>
<>child page id | child title<>
<><>child page id | child title<>
--- end parent 1 ---
--- start parent 2 ---
-- if first parent echo *
<>parent page id | parent title<>
--- parent 2 children ---
<>child page id | child title<>
<>child page id | child title<>
<>child page id | child title<>
--- end parent 2 ---
這種實現似乎運作良好,但我似乎無法弄清楚如何修改函數返回標記如上:
// Menu builder function, parentId 0 is the root
function buildMenu($parent, $menuData)
{
$html = "";
if (isset($menuData['parents'][$parent]))
{
$html .= "
<ul>\n";
foreach ($menuData['parents'][$parent] as $itemId)
{
if(!isset($menuData['parents'][$itemId]))
{
$html .= "<li>\n <a href='".$menuData['items'][$itemId]['link']."'>".$menuData['items'][$itemId]['label']."</a>\n</li> \n";
}
if(isset($menuData['parents'][$itemId]))
{
$html .= "
<li>\n <a href='".$menuData['items'][$itemId]['link']."'>".$menuData['items'][$itemId]['label']."</a> \n";
$html .= buildMenu($itemId, $menuData);
$html .= "</li> \n";
}
}
$html .= "</ul> \n";
}
return $html;
}
echo buildMenu(0, $menuData);