Implementation of Recursive Classification Algorithm for php Menu and Comment Data

  • 2021-12-13 07:49:26
  • OfStack

In the development process, we often encounter grading scenarios, such as menu grading, comments, commodity type grading and so on; It is possible to design a single table structure in the same mysql data table, as follows:


 $menuList = [
  [ 'id' => 1,'parent_id' => 0, 'name' => ' Node 1'],
  [ 'id' => 2,'parent_id' => 1, 'name' => ' Node 1-1'],
  [ 'id' => 3,'parent_id' => 0, 'name' => ' Node 2'],
  [ 'id' => 4,'parent_id' => 3, 'name' => ' Node 2-1'],
  [ 'id' => 5,'parent_id' => 2, 'name' => ' Node 1-1-1'],
  [ 'id' => 6,'parent_id' => 1, 'name' => ' Node 1-2'],
 ];

At this time, in the process of processing presentation, it is necessary to transform the above structure into a more intuitive data structure, such as:


$treeList = [
 [
 children: [
  children: []
 ]
 ]
 [,
 children: [
  children: []
 ]
 ]
];

The algorithm code is as follows:


<?php

class Menu
{
 /**
  *  Recursive loop menu list ,  Convert to menu tree 
  * @param $treeList  Menu tree list 
  * @param $menuList  Menu list 
  * @return bool
  */
 public function getMenuTree(&$treeList, $menuList)
 {
  //  Initialize the top-level parent node 
  if (! count($treeList)) {
   foreach($menuList as $index => $menu) {
    if ($menu['parent_id'] == 0) {
     $treeList[] = $menu;
     unset($menuList[$index]);
    }
   }
  }

  //  Recursive lookup of child nodes 
  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 {
    //  Recursive critical point 
    return false;
   }
  }
 }

}

$menuList = [
 [ 'id' => 1,'parent_id' => 0, 'name' => ' Node 1'],
 [ 'id' => 2,'parent_id' => 1, 'name' => ' Node 1-1'],
 [ 'id' => 3,'parent_id' => 0, 'name' => ' Node 2'],
 [ 'id' => 4,'parent_id' => 3, 'name' => ' Node 2-1'],
 [ 'id' => 5,'parent_id' => 2, 'name' => ' Node 1-1-1'],
 [ 'id' => 6,'parent_id' => 1, 'name' => ' Node 1-2'],
];
$treeList = [];
(new Menu)->getMenuTree($treeList, $menuList);
print_r($treeList);

happy coding!

Every day that never dances is a disappointment to life

Summarize


Related articles: