Home > Backend Development > PHP Tutorial > PHP recursion classic case

PHP recursion classic case

angryTom
Release: 2023-04-07 15:50:01
forward
3116 people have browsed it

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
Copy after login

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);
Copy after login

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!

Related labels:
source:www.whmblog.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template