Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Examples help you understand php recursive function principles and call methods


May 11, 2021 PHP


Table of contents


When learning recursive functions, the whites may not be able to understand the principle and operating mechanism of recursive functions, recursive functions are commonly used to a class of functions, the most basic feature is that the function itself calls itself, but must be conditional judgment before calling itself, if the conditions are met, then call the function itself, if not satisfied, then terminate the function's self-call, and then the current process of the main control to the previous layer of functions to execute, otherwise it will be unlimited call. Here are three basic ways php implements recursive functions.


First, the use of references as parameters

First, regardless of whether the reference does not do the argument, you must first understand what the reference is? A reference, however, means that two variables with different names point to the same storage address. O riginally each variable had its own storage address, and the assignment deleted each line. N ow it's okay that two variables share a storage address. $ a=&$b; 。 I n fact, $a, regardless of their original storage address, have to $b room with the company. T herefore, any change to the stored address value affects both values.
Functions are supposed to have rows between them, even if they have the same name. R ecursive functions consider references as arguments to form a bridge to form a data sharing between two functions. Although the two functions appear to operate at different addresses, they actually operate on a piece of child 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 short answer, with a-lt;10 as the condition of judgment, the condition is established, then assign a to the result; P assing a reference to the result into the function adds each recursively generated a to the resulting array result. So the $result array generated by this example is array ( . 1 .

What is more interesting in this example is the value of echo a. I believe a lot of people think it's 12345678910, but it's not, it's 1098765432. W hy is that? B ecause the function recursives the next function before it executes echoa. The real execution of echo a is when the a-lt;10 condition is not met, echo a, returns to the result, for the upper layer, after executing the recursive function, starting to execute the echo $a of this layer, and so on.

Second, the use of global variables

By using global variables to complete recursive functions, make sure that you really understand what a global variable is. G lobal states within a function that a variable is nothing more than a reference to the name of an external variable. T he scope of the variable is still within the scope of this function. C hange the value of these variables, and the value of the external variable with the same name naturally changes. B ut once used, variables with the same name are no longer references with the same name. Using global variables to implement recursive functions does not need to understand such a deep layer, but also to maintain the original view of global variables can be a logical understanding of recursive functions.
function test($a=0,$result=array()){
  global $result;
  $a++;
  if ($a<10) {
    $result[]=$a;
    test($a,$result);
  }
  return $result;
}

Third, the use of static variables

We often see static in classes, and today we take advantage of it in recursive functions. Remember what static does: initialize the variable only the first time you call the function, and keep the value of the variable.
For example:
function test(){
static $count=0;
echo $count;
 
$count++;
}
test();
test();
test();
test();
test();
What is the execution result of this piece of code? I s it 00,000? I t must not be. Y es 01234. F irst of all, the first call test(), static initialization of $count, after each execution will retain the value of $count, no longer initialization, equivalent to directly ignoring the static $count-0; This sentence.
So it's expected that the act of applying static to recursive functions. The variable that needs to be used as a "bridge" between recursive functions is initialized using 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;
}

Summary

The so-called recursive function, the focus is on how to deal with the function call itself how to ensure that the desired results can be reasonably "passed" between functions, of course, there is no need to pass between functions worthy of recursive functions, such as:
function test($a=0){
  $a++;
  if ($a<10) {
    echo $a;
 
    test($a);
  }
}

The php function recursively calls the instance

function arrContentReplact($array)
  {
  if(is_array($array))
  {
  foreach($array as $k => $v)
  {
  $array[$k] = arrContentReplact($array[$k]);
  }
  }else
  {
  $array = str_replace(
  array('<', '>'),
  array('{', '}'),
  $array
  );
  }
  return $array;
  }
  $arr = array(array("< 小刚>","< 小晓>",array("<小强>",array("<浪人>"))),"< 小飞>","< 小李>","< 小红>");
  $arr3 = arrContentReplact($arr);
  echo "
";
 
  print_r($arr3);

  echo "
";
 
  ?>

PHP recursively implements infinite classification

In some complex systems, unlimited classification of information columns is required to enhance the flexibility of the system. S o how does PHP achieve infinite classification? Here's how to use recursive algorithms and combine mysql data sheets for infinite classification.

1、Mysql
First, we prepare a data sheet class to record the product classification information. There are three fields in the table, id: category number, primary key self-growth; title: classification name; pid: parent classification 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 the data, figure:

Examples help you understand php recursive function principles and call methods


2、PHP
Depending on the requirements, we offer two custom functions in different formats, one return string, one return array, and both use recursive methods. Let's start by looking 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);//查询pid的子类的分类 
    if($result && mysql_affected_rows()){//如果有子类 
        $str .= '<ul>'; 
        while ($row = mysql_fetch_array($result)) { //循环记录集 
            $str .= "<li>" . $row['id'] . "--" . $row['title'] . "</li>"; //构建字符串 
            get_str($row['id']); //调用get_str(),将记录集中的id参数传入函数中,继续查询下级 
        } 
        $str .= '</ul>'; 
    } 
    return $str; 
} 
The above function get_str() by recursion, constantly querying sub-categories, and eventually returning strings, you can modify the str according to the needs of the project, and eventually generate an infinite list of ratings:
include_once('connect.php'); //连接数据库,connect.php文件自己写一个啊 
echo get_str(0); //输出无限级分类 

The effect is as shown in the figure:

Examples help you understand php recursive function principles and call methods

Then let's look at the functions that return the array format, just as we use recursion:
function get_array($id=0){ 
    $sql = "select id,title from class where pid= $id"; 
    $result = mysql_query($sql);//查询子类 
    $arr = array(); 
    if($result && mysql_affected_rows()){//如果有子类 
        while($rows=mysql_fetch_assoc($result)){ //循环记录集 
            $rows['list'] = get_array($rows['id']); //调用函数,传入参数,继续查询下级 
            $arr[] = $rows; //组合数组 
        } 
        return $arr; 
    } 
} 
Function get_array() returns an array, which is what we expect, so it is recommended to use get_array() to get the array, so that we can do anything about the array, for example, we can convert the array into a jason format of data to the front page, the front page can be resolved jason data flexible display classification information. For example, a list of classifications for tree structures, a list of down-down categories, and so on.
include_once('connect.php'); //连接数据库 
$list = get_array(0); //调用函数 
print_r($list); //输出数组 

Output:

Examples help you understand php recursive function principles and call methods

If you want to output data in jason format, you can use:
echo json_encode($list);