当前位置 : 主页 > 网络编程 > PHP >

PHP 实现递归调用

来源:互联网 收集:自由互联 发布时间:2021-06-28
这是一个地名,json格式,需要转换成数组或对象形式 $json='[{"id":9,"address":"上海","parent_id":0},{"id":1,"address":"安徽","parent_id":0},{"id":2,"address":"江苏","parent_id":0},{"id":3,"address":"合肥","parent_
这是一个地名,json格式,需要转换成数组或对象形式
$json='[
		{"id":9,"address":"上海","parent_id":0},
		{"id":1,"address":"安徽","parent_id":0},
		{"id":2,"address":"江苏","parent_id":0},
		{"id":3,"address":"合肥","parent_id":1},
		{"id":4,"address":"庐阳区","parent_id":3},
		{"id":5,"address":"大杨镇","parent_id":4},
		{"id":6,"address":"南京","parent_id":2},
		{"id":7,"address":"玄武区","parent_id":6},
		{"id":8,"address":"梅园新村街道","parent_id":7},
		{"id":16,"address":"梅园新村小区","parent_id":8},
		{"id":17,"address":"蔷薇园","parent_id":16},
		{"id":18,"address":"三号楼","parent_id":17},
		{"id":10,"address":"黄浦区","parent_id":9},
		{"id":11,"address":"外滩","parent_id":10},
		{"id":12,"address":"安庆","parent_id":1},
		{"id":13,"address":"浙江","parent_id":0},
		{"id":14,"address":"嘉兴","parent_id":13},
		{"id":15,"address":"河南","parent_id":0}
	]';
这是字符串格式,需要转换成数组,转换成数组的语句如下
//首先这是字符串,需要转换成数组才能被调用
$json  = json_decode($json,true);
//打印下看看是不是数组,如果是,才能对其进行调研
print_r($json);
下面就用到,递归循环调用
//定义一个函数城市树,里面传递参数
	function City_tree($json,$id,$step){
		//静态调用方法
		static $tree=[];
		//遍历出数组中的值
		foreach ($json as $key => $value){
			//数组的key值必须与id值相同
			if($value['parent_id']==$id){
				//添加拼接字符--
				$flg=str_repeat('--',$step);
				$value['address']=$flg.$value['address'];
				$tree[] = $value;
				//执行循环
				City_tree($json,$value['id'],$step+1);
			}
		}
		return $tree;
	}
	$tree = City_tree($json,0,0);
	foreach ($tree as $value1){
    	echo $value1['address'].'
'; }
最后实现的,结果为:
上海
--黄浦区
----外滩
安徽
--合肥
----庐阳区
------大杨镇
--安庆
江苏
--南京
----玄武区
------梅园新村街道
--------梅园新村小区
----------蔷薇园
------------三号楼
浙江
--嘉兴
河南
网友评论