在開發過程中經常會遇到分級場景,如菜單分級、評論、商品類型分級等;在同一張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: [] ] ]];
算法代碼如下:
<?phpclass 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);
happy coding!
每一個不曾起舞的日子,都是對生命的辜負 ^-^
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選