我有一个地区表,如下:
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;
}
怎么递归?

解决方案 »

  1.   

    1.使用递归没有关系,但是递归中查询数据库就有问题了.2. 这个用sql不就直接ok了? select * from table where parentid = id 
      

  2.   

    上面代码与数据库不一至,实际这样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;
    }
      

  3.   

     select count(*) from table where parentid = id 
      

  4.   

    去phpchina基本版块搜索,有详细的讨论
      

  5.   

    去phpchina基本版块搜索,有详细的讨论
      

  6.   

    http://bbs.phpchina.com/viewthread.php?tid=80868&highlight=%CE%DE%CF%DE%B7%D6%C0%E0
      

  7.   

    我尝试过把 return getdistricts($value['id'], $distids);中的return去掉,返回值要更多,但还是不全