Php uses recursive methods to implement unlimited classification

Source: Internet
Author: User
Unlimited classification is a kind of classification technique, such as department organization, article classification, and Subject Classification. it is good to simply understand it as a classification. I believe many of my friends will want to create a website to improve their technology when learning PHP, such as enterprise websites and shopping mall websites. these are their latest functions and column management, we use an infinite classification method. next we will explore its deep implementation logic through learning about the infinite classification technology.

What is an infinite classification?

Unlimited classification is a kind of classification technique, such as department organization, article classification, and Subject Classification. it is good to simply understand it as a classification. As a matter of fact, there are too many categories in our life. clothes can be divided into men's and women's clothing, jackets and trousers, or by age group. Classification is everywhere, and classification is "unlimited ". I will not mention the necessity of unlimited classification here.

Introduction to the principle of unlimited classification

Infinite classification seems to be "too high". In fact, the principle is very simple. Unlimited classification requires not only clever code, but also the rationality of database design. To meet the infinite classification requirements, the database must have two Required fields: id and pid. Id is used to identify itself, while pid is used to indicate the parent level id. That is to say, each classification record not only describes itself, but also describes another id most closely related to it. The seemingly complex things have been solved by such a small trick.

Instance

Database creation

Table name: category

Id int primary key, auto-increment

Name varchar category name

Pid int parent class id. the default value is 0.

Pid of top-level classification is 0 by default. When we want to retrieve the subcategory tree of a specific category, the basic idea is recursion. of course, we do not recommend that you query the database every recursion due to efficiency issues, the common practice is to extract all categories and save them to the PHP array for processing. Finally, the results can be cached to improve the efficiency of the next request.
First, construct an original array, which can be pulled directly from the database:

$ Categories = array ('id' => 1, 'name' => 'PC', 'pid '=> 0), array ('id' => 2, 'name' => 'phone', 'pid '=> 0), array ('id' => 3, 'name' => 'notebooks ', 'pid '=> 1), array ('id' => 4, 'name' => 'desktop', 'pid '=> 1 ), array ('id' => 5, 'name' => 'smartphone ', 'pid' => 2), array ('id' => 6, 'name' => 'function', 'pid '=> 2), array ('id' => 7, 'name' => 'superscript ', 'pid '=> 3), array ('id' => 8, 'name' => 'gamely', 'pid' => 3 ),)

The goal is to convert it to the following structure:
Computer-notebook --- Super book --- game book-desktop phone-smartphone-function machine
If it is represented by an array, you can add a children key to store its subcategories:

Array (// 1 corresponds to the id to facilitate direct reading of 1 => array ('id' => 1, 'name' => 'PC', 'pid '=> 0, children => array (& array ('id' => 3, 'name' => 'docker', 'pid '=> 1, 'Children '=> array (// omitted here), & array ('id' => 4, 'name' => 'desktop', 'pid '=> 1, 'Children '=> array (// omitted here),), // Other categories omitted)

Processing process:

$ Tree = array (); // Step 1: use the category id as the array key and create the children Unit foreach ($ categories as $ category) {$ tree [$ category ['id'] = $ category; $ tree [$ category ['id'] ['Children '] = array ();} // The second part is to add each category to the children array of the parent class by reference, so that a tree structure can be formed after a traversal. Foreach ($ tree as $ k =>$ item) {if ($ item ['pid']! = 0) {$ tree [$ item ['pid '] ['Children'] [] = & $ tree [$ k] ;}} print_r ($ tree );

The output is 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 [pid] => 3 [children] => Array ()) [1] => Array ([id] => 8 [name] => game book [pid] => 3 [children] => Array ()))) [1] => Array ([id] => 4 [name] => Desktop [pid] => 1 [children] => Array ()))) [2] => Array ([id] => 2 [name] => mobile phone [pid] => 0 [children] => Array ([0] => Array ([ id] => 5 [name] => Intelligent Machine [pid] => 2 [children] => Array ()) [1] => Array ([id] => 6 [name] => function Machine [pid] => 2 [children] => Array ()))) [3] => Array ([id] => 3 [name] => notebook [pid] => 1 [children] => Array ([0] => Array ([ id] => 7 [name] => Super [pid] => 3 [children] => Array ()) [1] => Array ([id] => 8 [name] => game book [pid] => 3 [children] => Array ()))) [4] => Array ([id] => 4 [name] => Desktop [pid] => 1 [children] => Array ()) [5] => Array ([id] => 5 [name] => Intelligent Machine [pid] => 2 [children] => Array ()) [6] => Array ([id] => 6 [name] => function Machine [pid] => 2 [children] => Array ()) [7] => Array ([id] => 7 [name] => Super [pid] => 3 [children] => Array ()) [8] => Array ([id] => 8 [name] => game book [pid] => 3 [children] => Array ()))

Advantage: The relationship is clear, and it is easy to modify the upper-lower-level relationship.

Disadvantage: PHP is used for processing. if the number of classes is large, the efficiency will be reduced.

Extended ------- recursive functions

Recursive functions are commonly used. the most basic feature of a function is that the function itself calls itself, but it must be judged by conditions before it calls itself. Otherwise, it can be called infinitely. How can we implement recursive functions? This article lists three basic methods. Understanding it requires a certain amount of basic knowledge, including understanding global variables, references, and static variables. Recursive functions are also a good technique for solving infinite classification. If you are interested in unlimited classification, use the recursive function in php to implement unlimited classification. I use plain words to explain complex things. For more information, see the manual.

  Using references as parameters

No matter whether the reference is done or not, you must first clarify what the reference is? A reference refers to two variables with different names pointing to the same storage address. Each variable has its own storage address, and values are assigned to and deleted separately. Now, two variables share a storage address. $ A = & $ B ;. In fact, $ a has to share a room with $ B regardless of its original storage address. Therefore, any change to the storage address value will affect the two values.

Functions are different, even functions with the same name. Recursive functions take reference as parameters as a bridge to form data sharing between two functions. Although the two functions seem to operate on different addresses, they actually operate on a memory address.

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


In the preceding example, a <10 is used as the judgment condition. if the condition is true, a <10 is used as the judgment condition. if the condition is true, a is assigned to result []. PASS result []; the reference of result is passed into the function, and a generated by each recursion is added to the result array a and added to the result array result. Therefore, the $ result Array generated in this example is Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ).

What is interesting in this example is the value of echo. I believe many people think it is 12345678910. In fact, it is 1098765432. Why? Because the function has not executed the value of echoa. I believe many people think it is 12345678910. In fact, it is 1098765432. Why? Because the function has performed the next function recursion before it executes echoa. The true execution of echo a is that when a <10 is not met, echo a returns a and returns result. for the last layer, the recursive function is executed, start to execute echo $ a for this layer, and so on.

Use global variables

Make sure that you understand what global variables are. Global declares in the function that the variable is a reference of the same name of the external variable. The variable is still within the scope of this function. Changing the values of these variables naturally changes the values of external variables with the same name. However, once & is used, variables with the same name are no longer referenced by the same name. Using global variables to implement recursive functions does not need to understand such a deep layer. we can understand recursive functions simply by keeping the original view of global variables.

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


Use static variables

We often see static in the class. today we use it in recursive functions. Remember the role of static: initialize the variable only when the function is called for the first time, and keep the variable value.

Example:

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


What is the execution result of this code? Is it 00000? No. It is 01234. First, call test () and static to initialize $ count for the first time. The value of $ count will be retained after each execution and will not be initialized, it is equivalent to directly ignoring the static $ count = 0; statement.

So it is conceivable to apply static to recursive functions. Variables that need to be used as the bridge between recursive functions are initialized using static. The value of bridge variable is retained for each recursion.

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

Summary

The so-called recursive function focuses on how to process the function call itself and how to ensure that the required results can be reasonably "transferred" between functions. of course, there is also a need to pass between functions that are worthy of recursion, for example:

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

In the face of such functions, it is of great benefit to have a deep understanding of the variable reference knowledge to solve such problems.

Related articles:

Php recursion to implement an infinite classification tree

Expose the principle of php unlimited classification

Php unlimited classification implementation method analysis

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.