php菜單/評論數(shù)據(jù)遞歸分級算法的實現(xiàn)方法
在開發(fā)過程中經(jīng)常會遇到分級場景,如菜單分級、評論、商品類型分級等;在同一張mysql數(shù)據(jù)表中可能設(shè)計單表結(jié)構(gòu),如同如下數(shù)據(jù):
$menuList = [ [ 'id' => 1,'parent_id' => 0, 'name' => '節(jié)點1'], [ 'id' => 2,'parent_id' => 1, 'name' => '節(jié)點1-1'], [ 'id' => 3,'parent_id' => 0, 'name' => '節(jié)點2'], [ 'id' => 4,'parent_id' => 3, 'name' => '節(jié)點2-1'], [ 'id' => 5,'parent_id' => 2, 'name' => '節(jié)點1-1-1'], [ 'id' => 6,'parent_id' => 1, 'name' => '節(jié)點1-2'], ];
這時候在處理展示過程就需要將上面的結(jié)構(gòu)轉(zhuǎn)換為更加直觀的數(shù)據(jù)結(jié)構(gòu), 形如:
$treeList = [ [ children: [ children: [] ] ] [, children: [ children: [] ] ] ];
算法代碼如下:
<?php
class Menu
{
/**
* 遞歸循環(huán)菜單列表, 轉(zhuǎn)化為菜單樹
* @param $treeList 菜單樹列表
* @param $menuList 菜單列表
* @return bool
*/
public function getMenuTree(&$treeList, $menuList)
{
// 初始化頂級父節(jié)點
if (! count($treeList)) {
foreach($menuList as $index => $menu) {
if ($menu['parent_id'] == 0) {
$treeList[] = $menu;
unset($menuList[$index]);
}
}
}
// 遞歸查找子節(jié)點
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' => '節(jié)點1'],
[ 'id' => 2,'parent_id' => 1, 'name' => '節(jié)點1-1'],
[ 'id' => 3,'parent_id' => 0, 'name' => '節(jié)點2'],
[ 'id' => 4,'parent_id' => 3, 'name' => '節(jié)點2-1'],
[ 'id' => 5,'parent_id' => 2, 'name' => '節(jié)點1-1-1'],
[ 'id' => 6,'parent_id' => 1, 'name' => '節(jié)點1-2'],
];
$treeList = [];
(new Menu)->getMenuTree($treeList, $menuList);
print_r($treeList);
happy coding!
每一個不曾起舞的日子,都是對生命的辜負 ^-^
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關(guān)文章
PHP利用Cookie設(shè)置用戶30分鐘未操作自動退出功能
這篇文章主要介紹了PHP利用Cookie設(shè)置用戶30分鐘未操作自動退出功能,需要的朋友可以參考下2017-07-07
php curl獲取到j(luò)son對象并轉(zhuǎn)成數(shù)組array的方法
今天小編就為大家分享一篇php curl獲取到j(luò)son對象并轉(zhuǎn)成數(shù)組array的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
VB中的RasEnumConnections函數(shù)返回632錯誤解決方法
這篇文章主要介紹了VB中的RasEnumConnections函數(shù)返回632錯誤解決方法,使用MSDN中的例子在XP SP3系統(tǒng)上出現(xiàn)的錯誤,需要的朋友可以參考下2014-07-07
Zend Framework教程之Resource Autoloading用法實例
這篇文章主要介紹了Zend Framework教程之Resource Autoloading用法,結(jié)合實例形式分析了Resource Autoloading實現(xiàn)自動加載的原理及具體使用方法,需要的朋友可以參考下2016-03-03

