欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php菜單/評論數(shù)據(jù)遞歸分級算法的實(shí)現(xiàn)方法

 更新時間:2019年08月01日 10:30:31   作者:洪加煌  
這篇文章主要給大家介紹了關(guān)于php菜單/評論數(shù)據(jù)遞歸分級算法的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用php具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

在開發(fā)過程中經(jīng)常會遇到分級場景,如菜單分級、評論、商品類型分級等;在同一張mysql數(shù)據(jù)表中可能設(shè)計單表結(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'],
 ];

這時候在處理展示過程就需要將上面的結(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é)點(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!

每一個不曾起舞的日子,都是對生命的辜負(fù) ^-^

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論