求递归算法

floy 2008-10-30 10:37:05
我有一个地区表,如下:
id ,parentid,name
1 0 中国
2 1 上海
3 1 江苏
4 2 浦东
5 2 虹口
6 4 张江
7 4 金桥


现在想统计隶属下海的地区下共有多少子类,怎么写这个递归程序,我用下面的方法取得的结果不对

function getdistricts($distid = 0, $distids) {
global $_SGLOBAL;

if (empty ($distids)) $distids = $distid;
$sql = "select * from " . tname('district') . " where reid=$distid";
$query = $_SGLOBAL['db']->query($sql);
while ($value = $_SGLOBAL['db']->fetch_array($query)) {
$distids = $distids . "," . $value['id'];
echo $distids."<br>";
return getdistricts($value['id'], $distids);
}
return $distids;
}


怎么递归?
...全文
107 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
floy 2008-10-30
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 pqingliang 的回复:]
http://bbs.phpchina.com/viewthread.php?tid=80868&highlight=%CE%DE%CF%DE%B7%D6%C0%E0
[/Quote]
非常感谢你的回复,我正在看,谢谢!
floy 2008-10-30
  • 打赏
  • 举报
回复
我尝试过把 return getdistricts($value['id'], $distids);中的return去掉,返回值要更多,但还是不全
pqingliang 2008-10-30
  • 打赏
  • 举报
回复
http://bbs.phpchina.com/viewthread.php?tid=80868&highlight=%CE%DE%CF%DE%B7%D6%C0%E0
pqingliang 2008-10-30
  • 打赏
  • 举报
回复
去phpchina基本版块搜索,有详细的讨论
pqingliang 2008-10-30
  • 打赏
  • 举报
回复
去phpchina基本版块搜索,有详细的讨论
floy 2008-10-30
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 pqingliang 的回复:]
你的意思是,每条记录是一个分类树?
[/Quote]

是这样的,找出他所有子孙
floy 2008-10-30
  • 打赏
  • 举报
回复
需要的结果不只是第一层归属,而是统计所有包含的N级子类
pqingliang 2008-10-30
  • 打赏
  • 举报
回复
你的意思是,每条记录是一个分类树?
floy 2008-10-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 pqingliang 的回复:]
1.使用递归没有关系,但是递归中查询数据库就有问题了.

2. 这个用sql不就直接ok了? select * from table where parentid = id
[/Quote]
但我要的效果实际上这样:
4 2 浦东
5 2 虹口
6 4 张江
7 4 金桥

应该包含它的子类,及子类的子类...
pqingliang 2008-10-30
  • 打赏
  • 举报
回复
select count(*) from table where parentid = id
floy 2008-10-30
  • 打赏
  • 举报
回复
上面代码与数据库不一至,实际这样

function getdistricts($distid = 0, $distids) {
global $_SGLOBAL;

if (empty ($distids)) $distids = $distid;
$sql = "select * from district where parentid=$distid";
$query = $_SGLOBAL['db']->query($sql);
while ($value = $_SGLOBAL['db']->fetch_array($query)) {
$distids = $distids . "," . $value['id'];
echo $distids."<br>";
return getdistricts($value['id'], $distids);
}
return $distids;
}

pqingliang 2008-10-30
  • 打赏
  • 举报
回复
1.使用递归没有关系,但是递归中查询数据库就有问题了.

2. 这个用sql不就直接ok了? select * from table where parentid = id

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧