SoFunction
Updated on 2025-03-02

Implementation method of php menu/comment data recursive grading algorithm

During the development process, you often encounter grading scenarios, such as menu grading, comments, product type grading, etc.; a single table structure may be designed in the same mysql data table, as shown in the following data:

 $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 and display, the above structure needs to be converted into a more intuitive data structure, such as:

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

The algorithm code is as follows:

<?php

class Menu
{
 /**
   * Recursively loop the menu list, converting to menu tree
   * @param $treeList Menu Tree List
   * @param $menuList MenuList
   * @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]);
    }
   }
  }

  // Recursively search for 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 life-and-desperate life ^-^

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.