Home > Backend Development > PHP Tutorial > Use function recursion to achieve infinite classification

Use function recursion to achieve infinite classification

WBOY
Release: 2016-07-29 08:59:41
Original
1034 people have browsed it
<span style="font-size:18px;">/*
*利用函数递归的思想创建一个函数实现无限分类的功能
*其实就是以每条数据的f_id父id作为根节点,进行数据的串联,再以根节*点向下查找
*
*
*举例:id   f_id   title
*       1     0     陕西
*       2     0     山西
*       3     1     西安
*       4     1     渭南
*       5     2     山西
*我们以省市划分举例,id代表每条记录的序号,f_id代表父id,取值取得*是它的上一级区域的id。 仔细观察即可发现规律
*        个人理解,希望可以帮助有需求的人
*/

//创建一个函数两个参数 $arr 将分类的数组  $p_id 初始父id</span>
Copy after login
<span style="font-size:18px;">
</span>
Copy after login
<span style="font-size:18px;">
function get_fenlei($arr,$p_id=0){
	//采用foreach()循环打印$arr数组
	foreach ($arr as $value) {
   //首先我们寻找f_id==0的记录,因为它们是最高的,所以分别以它们
   //为根节点向下寻找子节点,即就是利用函数递归,寻找
   //属于直辖下的城市	
		if($value['p_id']==$p_id){//f_is==0执行

          if($value['p_id']==0){//为了显示效果,不是核心代码
                  echo "</br>".$value['title'];//显示title
          }else{
          	echo "</br>--------".$value['title'];
          }	
          //函数递归,此时以根节点的id作为父id寻找它下面的城市
          //核心代码,如此递归 显示无限分类	
            get_fenlei($arr,$value['id']);
		}
		

		}
	}
//我们就不用操作数据库了,用一个数组代替就可以了
$arr=array(array('id'=>'1','p_id'=>'0','title'=>'陕西'),
	array('id'=>'2','p_id'=>'0','title'=>'山西'),
    array('id'=>'3','p_id'=>'1','title'=>'西安'),
    array('id'=>'4','p_id'=>'1','title'=>'渭南'),
    array('id'=>'5','p_id'=>'2','title'=>'大同')
	);
//执行函数
get_fenlei($arr);</span>
Copy after login
Copy after login
<span style="font-size:18px;">效果图:</span>
Copy after login
Use function recursion to achieve infinite classification

The above introduces the use of function recursion to achieve infinite classification, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.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