PHP:递归地获取父对象的子对象
我有一个函数,它从我的数据库中获取父对象的所有子对象的ID。所以,如果我查找ID7,它可能会返回一个包含5、6和10的数组。然后我想做的是递归地找到这些返回ID的子项,依此类推,直到子项的最终深度 我曾试图编写一个函数来实现这一点,但我对递归感到困惑PHP:递归地获取父对象的子对象,php,recursion,parent-child,children,Php,Recursion,Parent Child,Children,我有一个函数,它从我的数据库中获取父对象的所有子对象的ID。所以,如果我查找ID7,它可能会返回一个包含5、6和10的数组。然后我想做的是递归地找到这些返回ID的子项,依此类推,直到子项的最终深度 我曾试图编写一个函数来实现这一点,但我对递归感到困惑 function getChildren($parent_id) { $tree = Array(); $tree_string; if (!empty($parent_id)) { // getOneLev
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的一维数组。嵌套集模型,而不是邻接列表模型
我可以建议您将节点存储在NSM而不是ALM下的数据库中吗 请注意,使用ALM(您正在使用的)获取子节点非常困难,这是可能的,但需要额外的工作。如果使用嵌套集模型,则可以在单个SQL查询中选择子节点或所有节点,甚至查找所有节点的深度 如果你在项目开发过程中还很年轻,我希望这能为你解决问题提供一些启示。现在的转换将为你以后省去很多麻烦。这项工作对我来说很好:
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)代码>
然后它将返回给定节点/父节点的完整子数组。而不是数组\u push($tree,$id)
try$tree=array\u merge($tree,$id)代码>。杀死$tree\u字符串。=内爆(',',$tree)
并返回$tree
。(一次)
使用邻接列表模型,更新/移动父级是否容易?不,更新ALM表需要很多查询。大约6~取决于您对查询的优化程度。这些好处都是在您选择时产生的。然后,您可以只执行一个查询,而不是执行4个查询来选择深度、子项、父项等。因此,如果您选择的内容多于插入和更新的内容,那么您应该使用ALM imho。这不是正好相反吗?使用嵌套集,通过选择与每个节点关联的左侧值并对其排序,可以非常轻松地检索完整的树(或树的任何子集)。有关更多信息,请参阅(特定于MySQL,但如果需要,应该可以方便地移植到另一个RDBMS)。反之亦然。我将编辑。:)我总是把它们搞混。我弄明白了,现在,我坚持使用NMS,因为我真正需要的是这个函数来做很多事情。这很好。你可能需要在课堂上把这两个都包装起来。我还在$tree=$this->getOneLevel($parent\u id)之后的右下方插入了代码代码>`foreach($tree as$branch=>$branch_string){if(在_数组中($branch_string,$tree_string)){unset($tree[$branch]);}}}`这看起来不对,如何用代码示例进行注释?
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;
}