我有一些問題讓樹形菜單從下往上工作。 我已經有一個腳本從上往下工作,工作正常。PHP樹形菜單,自底向上
這是我的表的一個非常簡化的版本:
+-----+-----------+--------------------+
| uid | parent_id | page_address |
+-----+-----------+--------------------+
| 1 | 0 | index.php |
| 2 | 0 | login.php |
| 3 | 2 | dashboard.php |
| 4 | 3 | bookings.php |
| 5 | 3 | documents.php |
| 6 | 4 | changebookings.php |
| 7 | 4 | activities.php |
+-----+-----------+--------------------+
的page_address領域是獨一無二的。
我可以計算出用戶當前所在的頁面,例如changebookings.php
我然後像一個菜單,如下所示:
login.php
dashboard.php
bookings.php
changebookings.php
activities.php
documents.php
然而,最近我有這麼遠是下面的樹:
login.php
bookings.php
changebookings.php
正如你所看到的,我的劇本目前只返回實際的父母,而不是目前在父鏈接列表。
對於那些感興趣的,我使用的腳本總是在這篇文章的底部。
有沒有更簡單的方法來根據需要獲取自下而上樹? 非常感謝
菲爾
編輯: 我終於拿到了代碼工作,爲在這個帖子誰絆倒未來的用戶,我已經添加了功能如下:
$dataRows = $databaseQuery->fetchAll(); // Get all the tree menu records
$dataRows = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($dataRows as $row)
{
if($row['link_address']==substr($_SERVER['PHP_SELF'], 1, strlen($_SERVER['PHP_SELF'])-1))
{
$startingId = $row['parent_id'];
}
}
$menuTree = $this->constructChildTree($dataRows, $startingId);
private function constructChildTree(array $rows, $parentId, $nesting = 0)
{
$menu = array();
if(!in_array($nesting, $this->nestingData))
{
$this->nestingData[] = $nesting;
}
foreach($rows as $row)
{
if($row['parent_id']==$parentId && $parentId!=0)
{
$menu[] = $row['link_address'];
$newParentId = $this->getNextParent($rows, $row['parent_id']);
$parentChildren = $this->constructChildTree($rows, $newParentId, ($nesting+1));
if(count($parentChildren)>0)
{
foreach($parentChildren as $menuItem)
{
$menu[] = 'NESTING' . $nesting . '::' . $menuItem;
}
}
}
}
return $menu;
}
private function getNextParent($rows, $parentId)
{
foreach($rows as $row)
{
if($row['uid']==$parentId)
{
return $row['parent_id'];
}
}
}
[存儲分層數據庫中的數據(http://www.sitepoint.com/hierarchical-data-database-2/) – DarkBee 2013-04-22 11:23:03