PHP:递归获取父级的子级

Nic*_*ard 3 php recursion children parent-child

我有一个函数可以从我的数据库中获取父项的所有子项的ID.因此,如果我查找id 7,它可能会返回一个包含5,6和10的数组.我当时想要做的是,递归地找到那些返回的id的子项,依此类推,直到子项的最终深度.

我曾尝试编写一个函数来执行此操作,但我对递归感到困惑.

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()
Run Code Online (Sandbox Code Playgroud)

函数运行后,我希望它返回一个找到的所有子id的一维数组.

小智 6

这对我来说很好:

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;
}
Run Code Online (Sandbox Code Playgroud)

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