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
3. Pass Recursively, list provinces and cities
$item = array( array('id'=>1,'pid' => 0, 'name'=>'广东省' ), array('id'=>2,'pid' => 0, 'name'=>'广西省' ), array('id'=>3,'pid' => 1, 'name'=>'深圳市' ), array('id'=>4,'pid' => 3, 'name'=>'宝安区' ), array('id'=>5,'pid' => 1, 'name'=>'广州市' ), ); function recursion($array, $pid = 0){ $arr = array(); foreach ($array as $v) { if ($v['pid'] == $pid) { $temp = array(); $temp = recursion($array, $v['id']); //判断是否存在子数组 if($temp) { $v['son'] = $temp; } $arr[] = $v; } } return $arr; } $array = recursion($item); echo "<pre class="brush:php;toolbar:false">"; print_r($array);
Rendering
## For more PHP related knowledge, please visitPHP 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!