How to implement infinite pole classification in PHP: Recursive method and Reference method

Source: Internet
Author: User

This article brings the content is about the PHP implementation of infinite Pole classification method: Recursive method and reference method, there is a certain reference value, the need for friends can refer to, I hope to help you.

The interview was asked about the design and implementation of the infinite Pole classification, and it is common practice to add a PID field to distinguish the categories you belong to when building a table.

The data is stored in the database probably this way, how to achieve infinite pole recursion, there are two common practices, recursion and reference algorithm

Recursive algorithm

    /** * Recursive implementation of infinite pole classification * @param $array categorical data * @param $pid Parent ID * @param $level classification level * @return $list array of good classes        Direct traversal $level can be used to traverse the indent */function Gettree ($array, $pid =0, $level = 0) {//Declare a static array, avoid recursive calls, multiple declarations cause array overrides        static $list = [];                foreach ($array as $key + $value) {//First traversal, find the node that is the root node of the parent node that is pid=0 node if ($value [' pid '] = = $pid) {                The parent node is the node of the root node and the level is 0, which is the first level $value [' levels '] = $level;                Put the array in the list $list [] = $value;                Remove this node from the array to reduce subsequent recursive consumption unset ($array [$key]);            Start recursion to find the node with the ID of the parent ID, the level is +1 gettree ($array, $value [' id '], $level + 1);    }} return $list;    }/* * Get recursive data, traverse generation classification */$array = Gettree ($array); foreach ($array) as $value {echo str_repeat ('--', $value [' Level ']), $value [' name '].    <br/> '; }//Output Results Infinite pole classification implementation OK Hebei--Hanhan----Yongnian District--Wuan Beijing--Chaoyang District----wangjing----Jiuxianqiao--Tongzhou District

Reference Algorithm

function Generatetree ($array) {//The first step constructs the data $items = Array ();    foreach ($array as $value) {$items [$value [' id ']] = $value;    }//second traversal data spanning tree structure $tree = array (); foreach ($items as $key = + $value) {if (Isset ($items [$item [' pid]]) {$items [$item [' pid ']][' son '] [] = &        amp; $items [$key];        }else{$tree [] = & $items [$key]; }} return $tree;}  After the first step the data becomes such that array ([1] = = Array ([id] = 1 [PID] + 0 [name] = = Hebei province [Children] = = Array ()) [2] = = Array ([                ID] + 2 [PID] + 0 [name] + Beijing [children] + = Array ( )) [3] = = Array ([id] = 3 [PID] + 1 [name] = + Han      Did city [children] = Array ()) [4] = = Array  ([id] = 4 [PID] + 2 [name] = Chaoyang District [Children] = = Array            ()) [5] = = Array ([id] = 5 [pid] = 2        [Name] = Tongzhou District [Children] = Array ()) [6] = = Array                ([id] = 6 [PID] + 4 [name] = Wangjing [children] = = Array ()) [7] = = Array ([id] = 7 [PID] = 4 [            Name] = Jiuxianqiao [children] = = Array ()) [8] = = Array (                [ID] + 8 [PID] + 3 [name] + Yongnian area [children] = = Array ()) [9] = = Array ([id] = 9 [PID] = 1 [na           Me] = Wuan [children] = = Array ())//The first step is easy to understand, that is, to construct the data, now let's take a closer look at the second step $tree = Array (); Traverse the constructed data foreach ($items as $key + $value) {//If the PID node exists if (Isset ($items [$value [' pid]])} {//            Put the current $value into the son of the PID node. Notice what is being referred to here?        $items [$value [' pid ']][' son '] [] = & $items [$key];        }else{$tree [] = & $items [$key]; }}//The core of this method is the reference, the default value of the PHP variable is passed by means of the----that is, if the traversal order is Hebei province Hanhan when traversing to Hebei province will put Hebei province into the tree in the Hanhan will put the Hanhan into the sub-node of Hebei province in the array but!!! In the tree array of the moment, Hebei province has put in a rule that is passed by value according to the PHP variable you did not change the data of Hebei Province in the tree array so here's the reference pass//When you make a change to Hebei province, Hebei Province in the tree array is also changed. Let's do an experiment.            We remove the reference pass, look at the result//Use normal value output array ([0] = = Array ([id] = 1 [pid] + 0 [name] = = Hebei province) [1] = = Array ([id] + 2 [PID] + 0 [name] BEIJING, China)//You can see only Hebei province and Beijing output because they are the first level node and ranked 1 and 2, put into the $tree array, not using the reference pass, then the subsequent operation of their child nodes are not in effect in $tree, now we change the order of the Hanhan putTo the front of Hebei province so according to our inference, then Hanhan should appear in the tree array//Hanhan put in the front of Hebei province output result Array ([0] = = Array ([id] = 1 [PID] = 0 [name] + Hebei province [son] + Array ([0] = Arra                            Y ([id] = 3 [pid] = 1 [name] + Hanhan)) [1] = = Array ([i D] + 2 [PID] + 0 [name] + Beijing))//That's how it turns out our inference is correct. Now let's change the value of the reference back and look at it.//Use the reference value output            Result Array ([1] = = Array ([id] = 1 [PID] + 0 [name] = = Hebei province                            [Children] = = Array ([0] = = Array (                            [ID] + 3 [PID] + 1 [name] = = Hanhan [Children] =&Gt                                        Array ([0] = = Array                                            ([ID] + 8 [pid] = 3                                [Name] = Yongnian District)                            )) [1] = = Array (                        [ID] + 9 [PID] + 1 [name] = = Wuan ))) [2] = = Array ([id] = 2 [pid] = 0 [name                             ] = Beijing [children] = = Array ([0] = = Array ( [id] = 4 [PID] + 2 [name] = =                 Chaoyang           [Children] = = Array ([0] = = Array                                            ([id] = 6                                        [PID] = 4 [Name] = Wangjing                                            ) [1] = = Array (                                            [id] = 7 [PID] + 4                        [Name] = Jiuxianqiao))                            ) [1] = = Array ([id] = 5 [PID] = 2 [name] = Tongzhou District))))//Tree The perfect output of the structure. The core of this method is the reference value. 

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.