3

I have a function which gets the ids of all children of a parent from my DB. So, if I looked up id 7, it might return an array with 5, 6 and 10. What I then want to do, is recursively find the children of those returned ids, and so on, to the final depth of the children.

I have tried to write a function to do this, but I am getting confused about recursion.

function getChildren($parent_id) {
    $tree = Array();
    $tree_string;
    if (!empty($parent_id)) {
        // getOneLevel() returns a one-dimentional array of child ids
        $tree = $this->getOneLevel($parent_id);
        foreach ($tree as $key => $val) {
            $ids = $this->getChildren($val);
            array_push($tree, $ids);
            //$tree[] = $this->getChildren($val);
            $tree_string .= implode(',', $tree);
        }

        return $tree_string;
    } else {
        return $tree;
    }

}//end getChildren()

After the function is run, I would like it to return a one-dimentional array of all the child ids that were found.

4

3 回答 3

7

这对我来说很好:

function getOneLevel($catId){
    $query=mysql_query("SELECT categoryId FROM categories WHERE categoryMasterId='".$catId."'");
    $cat_id=array();
    if(mysql_num_rows($query)>0){
        while($result=mysql_fetch_assoc($query)){
            $cat_id[]=$result['categoryId'];
        }
    }   
    return $cat_id;
}

function getChildren($parent_id, $tree_string=array()) {
    $tree = array();
    // getOneLevel() returns a one-dimensional array of child ids        
    $tree = $this->getOneLevel($parent_id);     
    if(count($tree)>0 && is_array($tree)){      
        $tree_string=array_merge($tree_string,$tree);
    }
    foreach ($tree as $key => $val) {
        $this->getChildren($val, &$tree_string);
    }   
    return $tree_string;
}

调用getChildren(yourid); Then 它将返回给定节点/父节点的完整子节点数组。

于 2010-04-20T12:09:37.093 回答
3

嵌套集模型而不是邻接表模型


我可以建议您将节点存储在 NSM 而不是 ALM 下的数据库中吗?

请注意,使用 ALM(这是您正在使用的)获取子节点非常困难,但这是可能的,但需要额外的工作。如果您使用嵌套集模型选择子节点或所有节点,甚至查找所有节点的深度,都可以在单个 SQL 查询中完成。

我希望这对您如何解决您的问题有所启发,如果您现在还处于开发项目的年轻状态,那么现在切换将为您以后省去很多麻烦。

于 2010-02-28T21:20:28.810 回答
1

而不是array_push($tree, $ids);尝试$tree = array_merge($tree, $ids);。杀之$tree_string .= implode(',', $tree);而刚return $tree。(一次)

function getChildren($parent_id) {
    $tree = Array();
    if (!empty($parent_id)) {
        $tree = $this->getOneLevel($parent_id);
        foreach ($tree as $key => $val) {
            $ids = $this->getChildren($val);
            a$tree = array_merge($tree, $ids);
        }
    }
    return $tree;
}
于 2010-04-20T13:12:04.853 回答