PHP uses recursive method to realize infinite class classification

Source: Internet
Author: User
I believe many small partners are learning PHP when they want to make a website to improve their technology, such as corporate web site, the mall site of their recent functions, column management, using the infinite classification method, we will then through the infinite level of classification technology learning to explore its deep realization of logic.

What is an infinite class classification?

Infinite class classification is a kind of classification skills, such as departmental organization, article classification, subject classification and so on to the infinite classification, it is simple to understand the classification is good. In fact, we think about it, the classification of life is simply too many, clothes can be divided into men's and women's clothing, can also be divided into tops and trousers, can also be classified according to age. Classification is everywhere, the classification appears "infinite". I'm not talking about the need for infinite categorization here.

Introduction to the principle of infinite class classification

The infinite classification seemingly "tall", in fact, the principle is very simple. Infinite classification needs not only the subtlety of code, but also the rationality of database design. To satisfy an infinite class of classifications, the database needs to have two required fields, Id,pid. The ID is used to identify itself, and the PID is used to indicate the parent ID. That is, each classification record not only describes itself, but also describes another ID that is most closely related to it. Seemingly complex things are solved by such a small skill.

Instance

Build Library

Table Name: Category

ID int primary KEY, self-increment

Name varchar category names

PID int parent class ID, default 0

The PID of the top category is 0 by default. When we want to take out the sub-classification tree of a classification, the basic idea is recursion, of course, for efficiency issues do not recommend each recursive query database, the general practice is to first say all the categories are taken out, saved to the PHP array, then processed, and finally can be cached to improve the efficiency of the next request.
Start by building a primitive array, which is simply pulled out of the database:

$categories = Array (    ' id ' =>1, ' name ' = ' computer ', ' pid ' =>0),    array (' ID ' =>2, ' name ' = ' phone ', ' PID ' =>0 ',    array (' ID ' =>3, ' name ' = ' notebook ', ' pid ' =>1),    array (' ID ' =>4, ' name ' = ' desktop ', ' pid ' = >1),    array (' ID ' =>5, ' name ' = ' smart machine ', ' pid ' =>2),    array (' ID ' =>6, ' name ' = ' function machine ', ' pid ' = 2),    array (' ID ' =>7, ' name ' = ' Super Ben ', ' pid ' =>3),    array (' ID ' =>8, ' name ' = ' game Ben ', ' pid ' =>3),

The goal is to turn it into the following structure
Computer-Notebook ——-Super Ben ——-game Ben-desktop phone-smart machine-function machine
With an array, you can add a children key to store its sub-categories:

Array (    //1 corresponding ID, easy to read directly    1 = = Array (        ' id ' =>1,        ' name ' = ' computer ',        ' pid ' =>0,        children= >array (            &array (                ' id ' =>3,                ' name ' = ' notebook ',                ' pid ' =>1,                ' Children ' =>array (                    ///omitted here                )            ,            &array (                ' id ' =>4,                ' name ' = ' desktop ', '                pid ' =>1,                ' Children ' =>array (                    ///omitted here)),)    ,    //other categories omitted)

Processing process:

$tree = Array ();//First step, use the class ID as the array key and create the Children unit foreach ($categories as $category) {    $tree [$category [' id '] = $ category;    $tree [$category [' id ']][' children '] = Array ();} Second, by using a reference, each classification is added to the parent class children array, so that a single traversal can form a tree structure. foreach ($tree as $k = + $item) {    if ($item [' pid ']! = 0) {        $tree [$item [' pid ']][' children '] = & $tree [$k];< C4/>}}print_r ($tree);

The printing results are as follows:

Array ([1] = = Array ([id] = 1 [name] + = computer [PID] + 0                            [Children] = = Array ([0] = = Array (                            [ID] + 3 [name] + notebook [pid] = 1                                        [Children] = = Array ([0] = = Array                                            ([id] = 7                                            [Name] = + Super ben [PID] = 3                                                [children] = = Array (                                        )) [1] = = Array         (                                   [ID] + 8 [name] + = game Ben                                                [PID] = 3 [children] = = Array                                        (                                                )                            ))) [1] = = Array (  [id] = 4 [name] + + desktop [pid] = =                        1 [children] = = Array () ))) [2] = = Array ([id] = 2 [name] =&gt ;                        Phone [PID] + 0 [children] = = Array ([0] = = Array      (                      [ID] + 5 [Name] = + Smart machine [PID] + 2                        [children] = = Array ()                            ) [1] = = Array ([id] = 6 [Name] + [PID] = 2 [children] =&gt ;     Array ()))) [3] = = Array ([id] = 3 [name] + notebook [PID] + 1 [chil                            dren] = Array ([0] = = Array (                            [id] = 7 [name] + super Ben [PID] + 3 [Children] = ArRay ()) [1] =&gt ;                            Array ([ID] + 8 [name] + = game Ben                                [PID] = 3 [children] = = Array (  ))) [4] = = Array ([id]                = 4 [name] + + desktop [PID] + 1 [children] + = Array (            )) [5] = = Array ([id] = 5 [Name] = + Smart machine [PID] + 2 [Children] = = Array ()) [6] = = Array ([id] =                > 6 [name] + [PID] = 2 [children] = = Array ( )) [7]= = Array ([id] = 7 [name] + super [PID] + 3 [children] =& Gt Array ()) [8] = = Array ([id] = 8 [name] =&G T Game Ben [PID] = 3 [Children] = Array ()))

Advantages: Clear relationship, modify the relationship between the subordinate simple.

Cons: With PHP processing, if the number of categories is large, the efficiency will be reduced.

Extended-------Recursive functions

Recursive functions are commonly used in a class of functions, the most basic feature is that the function itself calls itself, but must call itself before the conditional judgment, otherwise infinite infinite call down. What can be done to implement a recursive function? This article lists three basic ways of doing this. Understanding its original need for certain basic knowledge of water products, including the global variables, references, static variables of understanding, but also need to understand their scope of action. Recursive functions are also a good technique for solving infinite class classification. If you are interested in infinite class classification, please refer to PHP using recursive functions to achieve unlimited class classification. I'm used to explaining complicated things in plain words, you really don't understand. See the manual.

  Using references to make parameters

First of all, regardless of the reference do not do parameters, you must first understand what is the reference? A reference simply refers to a variable of two different names pointing to the same storage address. Each variable has its own storage address, and the assignment deletes the lines. Now, two variables share a single storage address. $a =& $b;. In fact, $a regardless of their original storage address, do not want to share a room with the $b. Therefore, any change to the value of the stored address will affect both values.

Functions are inherently fragmentation, even for functions with the same name. The recursive function is to consider the reference as a parameter, to become a bridge, to form a data share between two functions. Although the two functions seem to operate on a different address, the actual operation is a memory address.

function test ($a =0,& $result =array ()) {$a ++;if ($a <10) {    $result []= $a;    Test ($a, $result);} echo $a; return $result;}


The above example is very simple answer, take a<10 as the condition of judgment, the condition is set up, then a<10 as the condition of judgment, the condition is established, then assigns a to result[]; will result[]; the reference to the result is passed to the function, Each recursive generation of a is added to the result array a adds to the result array results. Thus this example generates an array of $result ([0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5 [5] = 6 [6] = 7 [7] = 8 [8] = 9).

The interesting thing about this example is the value of echo a. Believe that a lot of people think it is 12345678910, not actually, is 1098765432. Why is it? Because the function has not yet executed the value of Echoa. Believe that a lot of people think it is 12345678910, not actually, is 1098765432. Why is it? The next recursive function is performed because the function has not executed the Echoa. True echo A is when a is not satisfied when the a<10 condition is met, echo a, returns a, returns result, for the previous level, executes the recursive function, starts performing the echo $a of this layer, and so on.

Take advantage of global variables

Using global variables to complete the recursive function, make sure you do understand what global variables are. Global declares that a variable is simply a reference to an external variable with the same name. The scope of the variable is still within the scope of this function. Changing the values of these variables, the value of the external variable with the same name has changed naturally. But once & is used, the variable with the same name is no longer a reference with the same name. Using global variables to implement recursive functions it is not necessary to understand such a deep layer, but also to maintain the original view of global variables can logically understand the recursive function.

function test ($a =0, $result =array ()) {    global $result;    $a + +;    if ($a <10) {        $result []= $a;        Test ($a, $result);    }    return $result;}


Using static variables

We often see static in classes, and today we use it in recursive functions. Remember the function of static: Initializes the variable only the first time it is called, and retains the value of the variable.

Example:

function test () {static $count =0;echo $count; $count + +;} Test (); test (); test (); test (); test ();


What is the execution result of this section of code? Is it 00000? Not necessarily. Is 01234. First call test (), static $count initialization, after each execution will retain the value of $count, no longer initialized, equivalent to directly ignore the static$count=0; This sentence.

Thus it is conceivable to apply static to the function of recursion. Variables that need to be "bridges" between recursive functions are initialized with static, and each recursion retains the value of the bridge variable.

function test ($a =0) {    static $result =array ();    $a + +;    if ($a <10) {        $result []= $a;        Test ($a);    }    return $result;}

Summarize

The so-called recursive function, the focus is how to deal with the function call itself is how to ensure that the required results can be reasonably "passed" between functions, of course, there is no need to pass the function between functions worthy of recursive functions, for example:

function test ($a =0) {    $a + +;    if ($a <10) {        echo $a;        Test ($a);}    }

In the face of such a function, in-depth understanding of variable reference knowledge is useful for solving such problems.

Related articles:

PHP Recursive implementation of infinite-level classification tree

Uncover the principles of PHP infinite class classification

Analysis of implementation method of PHP infinite class classification

  • Related Article

    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.