php实现无限级分类,通过循环和递归实现

时间:2022-10-24 17:33:02

php无限极分类 

首先利用循环实现简单层次的展示

//使用PDO连接数据库

<?php
header("content-type:text/html;charset=utf-8");
$pdo = new PDO("mysql:host=127.0.0.1;dbname=ninthexam","root","root");
$rs = $pdo -> query("select * from city");
while($row = $rs -> fetch()){
    $data[] = $row;
}

//循环实现分类
foreach($data as $k=>$v)
{
    if($v['parint_id'] == 0)
    {
        $tmp[] = $v;
        foreach($data as $key=>$value)
        {
            if($v['city_id'] == $value['parint_id'])
            {
                $tmp[] = $value;
            }
        }
    }
}
echo "<pre>";
print_r($tmp);

//在使用递归的方式实现无限极分类展示

 //使用递归实现无限极分类
        function digui($data,$parint_id = 0 ,$cengji = 0)
        {
            //使用静态定义
            static $tmp = array();
            foreach($data as $k=>$v)
            {
                //判断如果层级ID==自增ID”
                if($v['parint_id'] == $parint_id)
                {
                    $v['cengji'] = $cengji;
                    $tmp[] = $v;
                    digui($data,$v['city_id'],$cengji+1);
                }
            }
            return $tmp;
        }
 print_r(digui($data,$parint_id = 0 ,$cengji = 0));
以上便是实现简单无限级分类的几种方式,望采纳。