PHP递归查找所有下级和所有上级
<?php $mysqli=new mysqli('127.0.0.1','root','root','test') or die(mysqli_error()); $mysqli->query('set names utf8') or die('设置编码出错!'); //递归无限查询下级 function getSong(&$mysqli,$pid=0,&$rowsArr=array(),$n=2){ $sql='SELECT id,name FROM user WHERE pid=\''.$pid.'\''; $rst=$mysqli->query($sql); $n=$n+3; while($row=$rst->fetch_assoc()){ $row['name']=str_repeat(' ',$n).'|-'.$row['name']; $rowsArr[]=$row; getParent($mysqli,$row['id'],$rowsArr,$n); } return $rowsArr; } //递归无限查询上级 function getParent(&$mysqli,$pid=0,&$rowsArr=array()){ $sql='SELECT pid,name FROM user WHERE id=\''.$pid.'\''; $rst=$mysqli->query($sql); while($row=$rst->fetch_assoc()){ $rowsArr[]=$row; getParent($mysqli,$row['pid'],$rowsArr); } return $rowsArr; }
代码如上,是使用的mysqli数据库查询
Dcr163的博客
http://dcr163.cn/107.html(转载时请注明本文出处及文章链接)