顶部导航开始 -->

递归无限分类

 $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}
	]';

    //定义一个函数城市树,里面传递参数
    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;
    }


    //首先这是字符串,需要转换成数组才能被调用
    $json  = json_decode($json,true);
//打印下看看是不是数组,如果是,才能对其进行调研
    echo '<pre>';
    print_r($json);

    $tree = City_tree($json,0,0);
    foreach ($tree as $value1){
        echo $value1['address'].'<br>';
    }


自学php博客
请先登陆后发表评论
  • 最新评论
  • 总共0条评论
  • © 2014-2016 zixuephp.cn 版权所有
  • ICP证:皖ICP备16012107号
  • 联系邮箱:510082587@qq.com
  • 交流请加微信:weibobf2899 或扫下方二维码