您好,登錄后才能下訂單哦!
這篇文章主要介紹php如何實現菜單/評論數據遞歸分級算法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
在開發過程中經常會遇到分級場景,如菜單分級、評論、商品類型分級等;在同一張mysql數據表中可能設計單表結構,如同如下數據:
$menuList = [ [ 'id' => 1,'parent_id' => 0, 'name' => '節點1'], [ 'id' => 2,'parent_id' => 1, 'name' => '節點1-1'], [ 'id' => 3,'parent_id' => 0, 'name' => '節點2'], [ 'id' => 4,'parent_id' => 3, 'name' => '節點2-1'], [ 'id' => 5,'parent_id' => 2, 'name' => '節點1-1-1'], [ 'id' => 6,'parent_id' => 1, 'name' => '節點1-2'], ];
這時候在處理展示過程就需要將上面的結構轉換為更加直觀的數據結構, 形如:
$treeList = [ [ children: [ children: [] ] ] [, children: [ children: [] ] ] ];
算法代碼如下:
<?php class Menu { /** * 遞歸循環菜單列表, 轉化為菜單樹 * @param $treeList 菜單樹列表 * @param $menuList 菜單列表 * @return bool */ public function getMenuTree(&$treeList, $menuList) { // 初始化頂級父節點 if (! count($treeList)) { foreach($menuList as $index => $menu) { if ($menu['parent_id'] == 0) { $treeList[] = $menu; unset($menuList[$index]); } } } // 遞歸查找子節點 foreach ($treeList as &$tree) { foreach ($menuList as $index => $menu) { if (empty($tree['children'])) { $tree['children'] = []; } if ($menu['parent_id'] == $tree['id']) { $tree['children'][] = $menu; unset($menuList[$index]); } } if (! empty($tree['children'])) { $this->getMenuTree($tree['children'], $menuList); } else { // 遞歸臨界點 return false; } } } } $menuList = [ [ 'id' => 1,'parent_id' => 0, 'name' => '節點1'], [ 'id' => 2,'parent_id' => 1, 'name' => '節點1-1'], [ 'id' => 3,'parent_id' => 0, 'name' => '節點2'], [ 'id' => 4,'parent_id' => 3, 'name' => '節點2-1'], [ 'id' => 5,'parent_id' => 2, 'name' => '節點1-1-1'], [ 'id' => 6,'parent_id' => 1, 'name' => '節點1-2'], ]; $treeList = []; (new Menu)->getMenuTree($treeList, $menuList); print_r($treeList);
以上是“php如何實現菜單/評論數據遞歸分級算法”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。