Home  >  Article  >  Backend Development  >  PHP recursion classic case

PHP recursion classic case

angryTom
angryTomforward
2019-10-14 18:24:553016browse

This article introduces you to the classic case of recursion.

1. What is a recursive function?

A function calling itself within its function body is called a recursive call. This kind of function is called a recursive function.

2. Understand php recursion in a few lines

function recursion($i){
 
    if($i<1){
        exit;    // 递归出口
    }
    echo $i."<br/>";
    recursion($i-1);
 
}
 
recursion(10); // 浏览器将显示从10显示到1

Rendering

PHP recursion classic case

3. Pass Recursively, list provinces and cities

$item = array(
    array(&#39;id&#39;=>1,&#39;pid&#39; => 0, &#39;name&#39;=>&#39;广东省&#39; ),
    array(&#39;id&#39;=>2,&#39;pid&#39; => 0, &#39;name&#39;=>&#39;广西省&#39; ),
    array(&#39;id&#39;=>3,&#39;pid&#39; => 1, &#39;name&#39;=>&#39;深圳市&#39; ),
    array(&#39;id&#39;=>4,&#39;pid&#39; => 3, &#39;name&#39;=>&#39;宝安区&#39; ),
    array(&#39;id&#39;=>5,&#39;pid&#39; => 1, &#39;name&#39;=>&#39;广州市&#39; ),
);
 
 
function recursion($array, $pid = 0){
 
    $arr = array();
    foreach ($array as $v) {
        if ($v[&#39;pid&#39;] == $pid) {
            $temp = array();
            $temp = recursion($array, $v[&#39;id&#39;]);
            //判断是否存在子数组
            if($temp)
            {
                $v[&#39;son&#39;] = $temp;
            }
            $arr[] = $v;
        }
    }
    return $arr;
     
}
 
 
$array = recursion($item);
echo "<pre class="brush:php;toolbar:false">";
print_r($array);

Rendering

PHP recursion classic case

## For more PHP related knowledge, please visit

PHP Chinese website!

The above is the detailed content of PHP recursion classic case. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:www.whmblog.cn. If there is any infringement, please contact admin@php.cn delete