Home > Backend Development > PHP Tutorial > 如何递归查询?

如何递归查询?

WBOY
Release: 2016-06-23 13:12:23
Original
1024 people have browsed it

我的数据库表名为aaa,内容如下。我如何递归查询父节点?

USER PUSER
16   
24             16
19            16
21             24
32           19

如查32:则查出:32 19和16所在行?我是这么写的,好像不行啊。应该怎么写?

$result=mysql_query("select * from `aaa` where user='32'    union all
   select h.*,h1. from `aaa` h join result h1 on h.user=h1.Puser",$link);
$row=mysql_fetch_row($result);


回复讨论(解决方案)

你都知道要递归查询了,那你怎么没去做呢?
大致这样

function foo($id) {  $res = array();  $rs = mysql_query("select * from aaa where user='$id'");  if($row = mysql_fetch_assoc($rs)) {    $res[] = $row;    $res = array_merge($res, foo($row['puser']));  }  return $res;}
Copy after login


一直搜寻,直到puser为空

$ids = array();function getuser($user){    global $ids;    $result=mysql_query("select * from `aaa` where user='".$user."'",$link);    $data=mysql_fetch_assoc($result);    if($data['puser']!=''){        $ids[] = $user;        getuser($data['puser']);    }}getuser(32);print_r($ids);
Copy after login

谢谢两位大神,这还是要用function的啊,我研究学习一下,谢谢两位大神。

对呀,递归就是函数自己调用自己

谢谢两位大神!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template