在開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)遇到分級(jí)場(chǎng)景,如菜單分級(jí)、評(píng)論、商品類型分級(jí)等;在同一張mysql數(shù)據(jù)表中可能設(shè)計(jì)單表結(jié)構(gòu),如同如下數(shù)據(jù):
$menuList = [
[ 'id' => 1,'parent_id' => 0, 'name' => '節(jié)點(diǎn)1'],
[ 'id' => 2,'parent_id' => 1, 'name' => '節(jié)點(diǎn)1-1'],
[ 'id' => 3,'parent_id' => 0, 'name' => '節(jié)點(diǎn)2'],
[ 'id' => 4,'parent_id' => 3, 'name' => '節(jié)點(diǎn)2-1'],
[ 'id' => 5,'parent_id' => 2, 'name' => '節(jié)點(diǎn)1-1-1'],
[ 'id' => 6,'parent_id' => 1, 'name' => '節(jié)點(diǎn)1-2'],
];
這時(shí)候在處理展示過(guò)程就需要將上面的結(jié)構(gòu)轉(zhuǎn)換為更加直觀的數(shù)據(jù)結(jié)構(gòu), 形如:
$treeList = [
[
children: [
children: []
]
]
[,
children: [
children: []
]
]
];
算法代碼如下:
?php
class Menu
{
/**
* 遞歸循環(huán)菜單列表, 轉(zhuǎn)化為菜單樹(shù)
* @param $treeList 菜單樹(shù)列表
* @param $menuList 菜單列表
* @return bool
*/
public function getMenuTree($treeList, $menuList)
{
// 初始化頂級(jí)父節(jié)點(diǎn)
if (! count($treeList)) {
foreach($menuList as $index => $menu) {
if ($menu['parent_id'] == 0) {
$treeList[] = $menu;
unset($menuList[$index]);
}
}
}
// 遞歸查找子節(jié)點(diǎn)
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 {
// 遞歸臨界點(diǎn)
return false;
}
}
}
}
$menuList = [
[ 'id' => 1,'parent_id' => 0, 'name' => '節(jié)點(diǎn)1'],
[ 'id' => 2,'parent_id' => 1, 'name' => '節(jié)點(diǎn)1-1'],
[ 'id' => 3,'parent_id' => 0, 'name' => '節(jié)點(diǎn)2'],
[ 'id' => 4,'parent_id' => 3, 'name' => '節(jié)點(diǎn)2-1'],
[ 'id' => 5,'parent_id' => 2, 'name' => '節(jié)點(diǎn)1-1-1'],
[ 'id' => 6,'parent_id' => 1, 'name' => '節(jié)點(diǎn)1-2'],
];
$treeList = [];
(new Menu)->getMenuTree($treeList, $menuList);
print_r($treeList);
happy coding!
每一個(gè)不曾起舞的日子,都是對(duì)生命的辜負(fù) ^-^
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
您可能感興趣的文章:- php求斐波那契數(shù)的兩種實(shí)現(xiàn)方式【遞歸與遞推】
- PHP實(shí)現(xiàn)無(wú)限極分類的兩種方式示例【遞歸和引用方式】
- PHP利用遞歸函數(shù)實(shí)現(xiàn)無(wú)限級(jí)分類的方法
- PHP自定義遞歸函數(shù)實(shí)現(xiàn)數(shù)組轉(zhuǎn)JSON功能【支持GBK編碼】
- PHP遞歸寫(xiě)入MySQL實(shí)現(xiàn)無(wú)限級(jí)分類數(shù)據(jù)操作示例
- PHP數(shù)組遞歸排序?qū)崿F(xiàn)方法示例
- PHP迭代與遞歸實(shí)現(xiàn)無(wú)限級(jí)分類
- PHP實(shí)現(xiàn)遞歸的三種方法