PHP Recursive Algorithm Classic example

Source: Internet
Author: User

A recursive function is a self calling function that calls itself directly or indirectly in the body of a function. However, you need to set the conditions of the call, if the conditions are met, then call the function itself, if not satisfied with the termination of the function of the call, and then the current process of the main control back to the previous layer of functions to perform, it may be explained to you, or difficult to understand, Directly on the example

function test ($n) {

echo $n. "";

if ($n >0) {

Test ($n-1);

} else{

echo "<?>";

}

echo $n. ""

}

Test (2)

The final output of this example is 2 1 0<?>0 1 2.

I'll explain why the output is like this.

The first step is to execute Test (2), Echo 2, and then because of 2>0, execute test (1), followed by Echo 2 with no time to execute.
In the second step, execute Test (1), Echo 1, and then because of 1>0, execute test (0), and then there's no time to execute echo 1
Step three, execute test (0), Echo 0, execute test (0), Echo 0, at which point the condition of the 0>0 is not satisfied, the test () function is not executed, but the echo "<?>", and the following echo 0

At this point, the function no longer calls itself, and begins to return the master control of the process to the previous layer of functions to perform, which is to start execution of all the test () functions just before the output of the last echo,0 layer is 1 is the output 1 1 of the previous layer is 2 is the output 2 2 No mountain layer, so the output of the content is 2 1 0<?>0 1 2


How to consider using PHP recursive algorithm to solve the problem

For example: Ask S=1+2+3+4+5+6+......+n originally this question we used to use cyclic accumulation method. And here, if you want to use the recursive method, you have to consider two points:
1) Whether the problem can be converted into a recursive form of description;
2 whether there is a recursive end of the boundary conditions.

There are obviously two conditions for recursion:

1 s (n) =s (n-1) +n
2 S (1) =1
So the source program is:

int progression (int n) {

int res;   

if (n=1) Res=1 else res=progression (n-1) +n;   return

Res;

}

Sequential traversal of binary tree

void Inorder (Bintree t) {

if (t) {

inorder (t->lchild);   

printf ("%c", t->data);   

inorder (T->rchild);

}   

}

Mysql

First we prepare a data table class to record the product classification information. There are three fields in the table, ID: Category number, primary key from growth; title: category name; PID: the owning parent category ID.

Class table structure:

CREATE TABLE IF not EXISTS ' class ' (

' id ' mediumint (6) isn't null auto_increment,

' title ' varchar NOT NULL ,

' pid ' mediumint (6) Not NULL default ' 0 ',

PRIMARY KEY (' id ')

) Engine=myisam DEFAULT Charset=utf8;

After inserting the data, as shown in the figure:

Depending on the requirements, we provide two different forms of custom functions, one is to return the string, one is to return the array, both of the functions use recursive methods. First look at the function that returns the string format:

Function get_str ($id  = 0)  {      global  $str;        $sql  =  "select id,title from class where pid=  $id";         $result  = mysql_query ($sql);//query PID subclass of categories        if ($result  && mysql_affected_rows ()) {//If there are subcategories             $str  .=  ' <ul> ';          while   ($row  = mysql_fetch_array ($result))  { //cyclic recordset                 $str  .=  "<li>"  .  $row [' id '] .  ']- -" .  $row [' title '] . " </li> ";  //build string                get_str ($row [' id '])  //call GET_STR (), pass the ID parameter in the recordset to the function, and continue querying the lower            }           $str  .=  ' </ul> ';      }      return  $str; }

The above function get_str () through recursion, continuously inquires the subordinate classification, and finally returns the string, everybody can revise the STR according to the project demand, finally produces an infinite rank list:

Include_once (' connect.php '); Connect database, connect.php file write one yourself.

echo get_str (0);//Output Infinite class classification

Effects such as:

Then we'll look at the function that returns the array format, using recursion as well:

function get_array ($id =0) {       $sql  =   "select id,title from class where pid=  $id";      

$result  = mysql_query ($sql)//query subclass        $arr  = array ();      if ($result  && mysql_affected_rows ()) {//If there are subcategories            while ($rows =mysql_fetch_assoc ($result)) { //Circular recordset                 $rows [' list '] = get_array ($rows [' id '])  / /Call function, pass in parameters, continue query subordinate                $arr [] =   $rows;  //combined array           }           return  $arr;      } } 

function Get_array () returned the array, which is what we expected, so the author recommends using Get_array () to get the array, so that we can do any operation on the array, for example, we can convert arrays into JSON-formatted data to the front page, The front-end page can display the classification information flexibly by parsing the JSON data. For example, the tree structure of the classification list, Drop-down category list, and so on.

Include_once (' connect.php '); Connection database

$list = get_array (0);//Call Function

Print_r ($list);//output array

If you want to output JSON-formatted data, you can use:

echo Json_encode ($list);

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.