Typical Example of php recursive algorithm-PHP source code

Source: Internet
Author: User
The PHP recursive algorithm is a function call function. The operation is very simple. Next we will introduce you to the PHP recursive algorithm and some actual recursive usage. The PHP recursive algorithm is a function call function. The operation is very simple. Next we will introduce you to the PHP recursive algorithm and some actual recursive usage.

Script ec (2); script

A recursive function is a self-called function that calls itself directly or indirectly in the function body. However, you must set the self-called conditions. If the conditions are met, the function itself is called, if not, terminate the self-call of the function and return the current process's Main Control Right to the previous function for execution. This may be difficult to understand.

function test ($n){echo $n.”  “;if($n>0){test($n-1);}else{echo “
 ”;}echo $n.”  ”}test(2)

In this example, the final output result is 2 1 0. 0 1 2

I will explain why the output is like this.

Step 1: Execute test (2), echo 2, and then execute test (1) Because 2> 0. There is still echo 2 that can be executed later.
Step 2: Execute test (1), echo 1, and then execute test (0) because 1> 0. Similarly, echo 1 is not executed in time.
Step 3: Execute test (0), echo 0, execute test (0), echo 0. At this time, the 0> 0 condition is not met, and the test () function is not executed, but echo" And run echo 0.

At this time, the function no longer calls itself, and begins to return the main control right of the process to the previous function for execution, that is, to execute the last echo that has just been output by all the test () functions, the first layer of 0 is 1, that is, the last layer of output 1 is 2, that is, output 2 2 is not a mountain layer, so the output content is 2 1 0. 0 1 2


How to Use PHP recursive algorithms to solve the problem

For example, calculate s = 1 + 2 + 3 + 4 + 5 + 6 + ...... + N we used to accumulate loops for this problem. To use recursive methods, you must consider the following two points:
1) whether the problem can be converted into a recursive description;
2) whether there is a boundary condition for Recursive termination.

Obviously, both recursive conditions have:

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

int progression(int n){   int res;   if (n=1 )res=1 else res=progression(n-1)+n;   return res;   }

Traversing a binary tree in ascending order

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 category information. The table has three fields: id: Category Number, primary key auto-increment, title: category name, and pid: parent category id.

Class table structure:

CREATE TABLE IF NOT EXISTS `class` (   `id` mediumint(6) NOT NULL AUTO_INCREMENT,   `title` varchar(30) NOT NULL,   `pid` mediumint(6) NOT NULL DEFAULT '0',   PRIMARY KEY (`id`) ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

After inserting data,

Based on different requirements, we provide two types of custom functions in different formats, one is to return a string, the other is to return an array, and both functions use a recursive method. First, return the functions in string format:

Function get_str ($ id = 0) {global $ str; $ SQL = "select id, title from class where pid = $ id"; $ result = mysql_query ($ SQL ); // query the classification of the pid subclass if ($ result & mysql_affected_rows () {// if there is a subclass $ str. ='
 
 
    '; While ($ row = mysql_fetch_array ($ result) {// cyclic record set $ str. ="
  • ". $ Row ['id']." -- ". $ row ['title']."
  • "; // Construct the string get_str ($ row ['id']); // call get_str () to pass the id parameter in the record set to the function, continue to query lower-level} $ str. ='
';} Return $ str ;}

The above function get_str () continuously queries lower-level categories through recursion and returns a string. You can modify the str according to the project requirements to generate an unlimited rating list:

Include_once ('connect. php'); // connect to the database. Write an echo get_str (0) in the connect. php file. // output an infinite classification.

The effect is as follows:

Next, let's look at the functions that return the array format, and use 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 is a subclass while ($ rows = mysql_fetch_assoc ($ result )) {// cyclic record set $ rows ['LIST'] = get_array ($ rows ['id']); // call a function and input a parameter, continue to query lower-level $ arr [] = $ rows; // combined array} return $ arr ;}}

The get_array () function returns an array, which we expect. Therefore, we recommend that you use get_array () to obtain the array. In this way, we can perform any operation on the array, for example, we can convert the array into json format data and send it to the front-end page. The front-end page can flexibly display the category information by parsing json data. For example, the tree-like category list and drop-down category list.

Include_once ('connect. php'); // connect to the database $ list = get_array (0); // call the print_r function ($ list); // output an array

To output data in json format, 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.