PHP:递归获取父级的子级 [英] PHP: Recursively get children of parent
问题描述
我有一个函数,可从数据库中获取父级所有子级的ID。因此,如果我查找id 7,它可能会返回包含5、6和10的数组。然后,我要递归地找到返回的id的孩子,依此类推,直到孩子的最终深度。
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()
之后函数运行后,我希望它返回找到的所有子ID的一维数组。
After the function is run, I would like it to return a one-dimentional array of all the child ids that were found.
推荐答案
这项工作对我来说很好:
This work fine for me:
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);
然后它将返回给定节点/父级的完整子级数组。
Call the getChildren(yourid);
Then it will return the complete array of children for that given node/parent.
这篇关于PHP:递归获取父级的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!