search
HomeBackend DevelopmentPHP TutorialA brief introduction to the Infinitus classification tree structure

A brief introduction to the Infinitus classification tree structure

Aug 13, 2017 am 10:20 AM
ClassificationSimplestructure

The following editor will bring you a simple method to create an Infinitus classification tree structure. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

First, let’s take a look at the renderings

##The top category is actually a Second-level classification, second-level classification is also called a sub-category of first-level classification. On this basis, sub-categories can also have sub-categories, thus forming an infinite classification.

Let’s look at the specific implementation code:

1. Query by field in the controller to query all classification information (id: the ID value of the category, cate_name: the name of the category, pid: parent ID, sorts: preparation for displaying the title order, optional.)


public function cate_display()
  {
    $cate = D('Cate'); 
    $field = array('id','cate_name','pid','sorts');
    $list = $cate->allCategory($field);
    $this->assign('list',$list);
    $this->display();
  }

2. Code in the model

Create two methods in the model corresponding to the controller

1. Query all classification information, and Call the method to generate a classification tree:


public function allCategory($field='*'){
     $data = $this->field($field)->select();
     return $this->tree($data);
   }

2. Generate a classification tree (use recursion, pass in data, and pid[parent class id ], level [number of layers, used to control the number of displays] two variables, the initial value is zero)


public function tree($data,$pid=0,$level=0){
    static $tree = array();
    foreach($data as $k=>$v){
      if($v['pid'] == $pid){
        $v['level'] = $level;
        $tree[]=$v;
        $this->tree($data,$v['id'],$level+1);
      }
    }
  
    return $tree;
  }

3. Code in the view file


<p class="form-group">
        <label for="pid" class="col-sm-2 control-label no-padding-right">上级菜单</label>
        <p class="col-sm-6">
          <select name="pid" style="width: 100%;">
            <option selected="selected" value="0">顶级菜单</option>
            <volist name="row" id="val"> 
              <option value="{$val.id}"><?php echo str_repeat(&#39;-&#39;,$val[&#39;level&#39;]*4); ?>{$val.cate_name}
              </option> 
            </volist> 
          </select>
        </p>
      </p>

In this way, a classification tree structure that can be infinitely recursive is completed. Summary: The core idea is still the recursive function in the model, first pass in the pid default is zero. The pid passed in every time in the future is the id of the superior. Level is used to record the number of recursion levels. Finally, when the view page is displayed, the PHP built-in function str_repeat() is called to repeatedly output '-' to reach the output time. Distinguish the effect of progression.

The above is the detailed content of A brief introduction to the Infinitus classification tree structure. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool