Three methods of Infinitus classification (iteration, recursion, and reference)

Source: Internet
Author: User
Three methods of Infinitus classification:

  • One is the adjacency list, which is the form of id and parent id.

  • The other is the nested set, that is, the left and right values.

It is highly efficient to query the left and right values without recursion. it is recommended, but it is simple and intuitive without a pid, in addition, the structure design of some old databases, such as regions, has always been in the form of pid (it seems that some algorithms can convert the two, without in-depth understanding), so...

The following statements are in the form of adjacency list. the data table format is similar to id, pid, and name.

Generally, it is to read all the data from the database and then assemble an array to implement it. of course, you can also query the database every recursion, but it will cause pressure on the database, it is not easy to encapsulate it into a method. We do not recommend this.

Currently, there are three commonly used methods:

1. First, it is the most common and least efficient recursive method: it is a non-stop foreach loop recursion.


Function getTreeOptions3 ($ list, $ pid = 0) {$ options = []; foreach ($ list as $ key => $ value) {if ($ value ['id'] = $ pid) {// check whether the element is a child element, if yes, recursively query $ options [$ value ['id'] = $ value ['name']; unset ($ list [$ key]); // destroy the queried items to reduce the number of queries in the next recursion. $ optionsTmp = $ this-> getTreeOptions3 ($ list, $ value ['id']); // recursive if (! Empty ($ optionsTmp) {$ options = array_merge ($ options, $ optionsTmp) ;}} return $ options ;}


2. The second method is to use the recursion of the inbound and outbound stacks for calculation. The efficiency is better than the previous method, but it is also slow. The process is to first reverse the array, then fetch the top-level array into the stack, start the while loop, first go out of the stack and find out if there are any subnodes under it. if there are subnodes, the subnode is also added to the stack, the next while loop will check the subnode, and so on:


Function getTreeOptions2 ($ list, $ pid = 0) {$ tree = []; if (! Empty ($ list) {// first reverse the array, because the top $ list = array_reverse ($ list) will be given priority when the stack is released ); // first extract the top-level data and press it into the array $ stack. Then, remove $ stack = [] from $ list ($ list as $ key => $ value) {if ($ value ['pid '] ==$ pid) {array_push ($ stack, $ value); unset ($ list [$ key]);} while (count ($ stack) {// retrieve the first item from the stack $ info = array_pop ($ stack ); // query the remaining $ list pid with the same id, that is, find its subnode foreach ($ list as $ key => $ child) {if ($ child [pid] = $ info ['id']) {// if a subnode has a subnode, in the while loop, the sub-node array_push ($ stack, $ child); unset ($ list [$ key]);} // assembled into the drop-down menu format $ tree [$ info ['id'] = $ info ['name'] ;}} return $ tree ;}


3. use references for processing. this is really clever and the efficiency is the highest. for details, refer to the following:


/*** Data similar to the following format * [* 'id' => 1, * 'pid '=> 0, * 'items '=> [* 'id' => 2, * 'pid' => '1 '*... *] */Function getTree ($ list, $ pid = 0) {$ tree = []; if (! Empty ($ list) {// The list of objects whose names are id-based. $ newList = []; foreach ($ list as $ k => $ v) {$ newList [$ v ['id'] = $ v;} // then assemble it into a special format foreach ($ newList as $ value) {if ($ pid = $ value ['pid ']) {// first retrieve the top $ tree [] = & $ newList [$ value ['id'];} elseif (isset ($ newList [$ value ['pid ']) {// determine whether a non-top-level pid exists. If yes, then add the items field under the array where the pid is located, to store itself in $ newList [$ value ['pid '] ['items'] [] = & $ newList [$ value ['id'];} return $ tree ;}


Then recursively generate the select drop-down menu. due to the special format above, recursion is very fast:


Function formatTree ($ tree) {$ options = []; if (! Empty ($ tree) {foreach ($ tree as $ key => $ value) {$ options [$ value ['id'] = $ value ['name']; if (isset ($ value ['items ']) {// query whether a subnode exists $ optionsTmp = $ this-> formatTree ($ value ['items']); if (! Empty ($ optionsTmp) {$ options = array_merge ($ options, $ optionsTmp) ;}}} return $ options ;}


The above three methods do not matter for small data volumes, but they are very obvious for large data volumes. Comparison of the efficiency of the test results with 4000 regional data entries:

  • Method 1 (recursion) time consumption: about 8.9441471099854

  • Method 2 (iteration) time consumption: about 6.7250330448151

  • Method 3 (reference): about 0.028863906860352 elapsed time

I will go. The third method is against the sky. However, again, this is only a one-time read of a large amount of data, when the data volume is small, almost the same, not necessarily need to use the highest efficiency, it can also be implemented through other methods such as lazy loading.

By the way, encapsulate a class to add some padding or something. For more details, see the following class:

View Code

In the above records, if reprinted, please indicate the source address

The above is the details of the three methods of Infinitus classification (iteration, recursion, reference). For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.