$dsn = "mysql:host=127.0.0.1;port=3306;charset=utf8;dbname=store"; $pdo = new PDO($dsn,'root','root'); //print_r($pdo); function getTree($a=0,&$result=array(),$level=0){ //使用global使$pdo在方法里可以被访问到 global $pdo; //每次调用都让$level自增2 $level+=2; //sql语句 $sql = "select * from cate where parent_id ='$a'"; $res = $pdo->query($sql); while($row = $res->fetch(PDO::FETCH_ASSOC)){ //给名称加一个前缀 更容易让子类和父级分类区分开 $row['name'] = str_repeat('***',$level).$row['name']; $result[]=$row; //再次调用自身 getTree($row['cate_id'],$result,$level); } return $result; } function printcate(){ $arr = getTree(); $str = "<ul>"; foreach($arr as $k=>$v){ $str.="<li>".$v['name']."</li>"; } $str.="</ul>"; return $str; } echo printcate();