我有一个函数可以从我的数据库中获取父项的所有子项的 ID。因此,如果我查找 id 7,它可能会返回一个包含 5、6 和 10 的数组。然后我想做的是递归地找到那些返回的 id 的 child ,依此类推,直到 child 的最终深度。
我曾尝试编写一个函数来执行此操作,但我对递归感到困惑。
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 的一维数组。
最佳答案
这对我来说很好:
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);
然后它将返回给定节点/父节点的完整子节点数组。
关于PHP:递归获取父级的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2352689/