CMSPRESS 10 lines of code to get PHP unlimited classification 2

  • 2021-09-16 06:26:57
  • OfStack

Super unlimited classification uses simple and efficient core code with less than 10 lines
In addition, we seek the shortcomings of this classification and a more efficient and simple infinite classification method

The core code is as follows


class Tool {
  static public $treeList = array(); // Store unlimited classification results if 1 The page has multiple unlimited categories to use  Tool::$treeList = array();  Empty 
  /**
   *  Infinite classification 
   * @access public 
   * @param Array $data   // The result set obtained in the database  
   * @param Int $pid       
   * @param Int $count    // What level of classification 
   * @return Array $treeList  
   */
  static public function tree(&$data,$pid = 0,$count = 1) {
    foreach ($data as $key => $value){
      if($value['Pid']==$pid){
        $value['Count'] = $count;
        self::$treeList []=$value;
        unset($data[$key]);
        self::tree($data,$value['Id'],$count+1);
      } 
    }
    return self::$treeList ;
  }  
}

The result of saving sorting by $treeList [] is basically that unset ($data [$key]) can be saved after sorting once; Drop it because it can't be used anymore
& $data uses address-by-address referencing in conjunction with unset ($data [$key]); Reduce the number of cycles, which improves the efficiency several times.

However, it is necessary to sort Pid by ASC otherwise it will be incomplete

$value ['Count'] = $count; For the current level, a tree structure will be generated by level in the template

The data structure before and after sorting is as follows

Table required fields Id, Pid
Data structure before sorting
id pid
1 0
2 0
3 1
4 3

Sort data structure

id pid count
1 0 1
3 1 2
4 3 3
2 0 1


// Default list 
  public function index() {  
    $menu = M('Menu');
    $list = $menu->order('Pid ASC,Morder DESC,Id ASC')->select();
    $this->assign('List',Tool::tree($list));  
         $this->display();
  }

Called in the controller

< td style="text-indent: < {$vo['Count']*20} > px;" > < neq name="vo.Count" value="1" > | -- < /neq > < {$vo.Name} > < /td >

Template use < volist > Normal output can modify the fields that need spanning tree structure as above

If it is 3000, it takes 0.5 seconds. If it takes 1000, it takes about 0.02 seconds. If it exceeds 3000, the efficiency will be greatly reduced. The efficiency of about 2000 is still relatively high. No more detailed test has been carried out

If which big brother tested, please reply the test results


Related articles: