我正在使用通過遞歸爲我的網站構建導航的方法,而且我無法添加樣式。我的方法建立的方式我似乎無法找到一種方法來使父級父類和孩子一個孩子類,所以在CSS中我可以風格這兩個。在情況下,它會使事情變得更容易明白這裏是我的數據庫的一個例子:如何使用遞歸插入數據?
這裏的輸出我想要實現的一個例子:
<ul>
<li class="parent">Parent
<ul>
<li class="child">Child 1</li>
<li class="child">Child 2</li>
<li class="child">Child 3</li>
<li class="child">Child 4</li>
</ul>
</li>
</ul>
當前的代碼放子女在<li>
的每個實例中。我嘗試了很多不同的東西,這讓我很難過。下面的代碼:
/* i'm using pdo to pull all the categories out of MySQL, NULL means it will be a parent category */
$array = $categoryVIEW->fetchAll(PDO::FETCH_ASSOC);
$this->buildSide($array,NULL)
private function buildSide($items,$parent)
{
$hasChildren = false;
$outputHtml = '<ul>%s</ul>';
$childrenHtml = '';
foreach($items as $item)
{
if ($item['parent'] == $parent)
{
$hasChildren = true;
$childrenHtml .= '<li><a href="?c='.$item['category_id'].'">'.$item['category_name'];
$childrenHtml .= $this->buildSide($items,$item['category_id']);
$childrenHtml .= '</a></li>';
}
}
if (!$hasChildren)
{
$outputHtml = '';
}
return sprintf($outputHtml,$childrenHtml);
}
我敢肯定它的東西很容易,但我堅持:(
感謝在看看
UPDATE
我有!一直玩我的代碼,並添加了一個條件來檢查$parent
是NULL
,如果是這樣,使$class
父母,否則使$class
孩子。在每個孩子之後我都會收到一個不需要的<ul></ul>
?有什麼奇怪的是,當我改變$child = false;
它消除了我的錯誤<ul></ul>
,但使一切父母。根據您的編輯
private function buildSide($array,$parent)
{
$child = ($parent === NULL)?false:true;
$html = '';
$tag = '<ul>%s</ul>';
$class = ($child)?'child':'parent';
foreach($array as $item)
{
if($item['parent'] === $parent)
{
$child = true;
$html .= '<li class="'.$class.'">'.$item['category_name'];
$html .= $this->buildSide($array,$item['category_id']);
$html .= "</li>\n";
}
}
if(!$child)
{
$tag = '';
}
return sprintf($tag,$html);
}
你打電話給這個過程怎麼開始? '$ items'數組的數據結構是什麼?用單獨的例子來突出問題可能有助於解決問題。 – jheddings
嘿jheddings,謝謝你看看。我更新了我的代碼,以幫助更好地理解我想實現的目標。 – Mike