PHP:递归获取父级的子级
我有一个函数可以从我的数据库中获取父级的所有子级的 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()
函数运行后,我希望它返回找到的所有子 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()
After the function is run, I would like it to return a one-dimentional array of all the child ids that were found.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
而不是
array_push($tree, $ids);
尝试$tree = array_merge($tree, $ids);
。杀死$tree_string .= implode(',', $tree);
并返回 $tree
。 (一次)Rather than
array_push($tree, $ids);
try$tree = array_merge($tree, $ids);
. Kill the$tree_string .= implode(',', $tree);
and justreturn $tree
. (Once)我可以向您推荐这个有效的版本:
I can suggest you this version that works:
这对我来说效果很好:
调用
getChildren(yourid);
然后它将返回给定节点/父节点的完整子节点数组。
This work fine for me:
Call the
getChildren(yourid);
Then it will return the complete array of children for that given node/parent.
嵌套集模型而不是邻接列表模型
我可以建议您将数据库中的节点存储在 NSM 而不是 ALM 下吗?
请注意,使用 ALM(您正在使用的)获取子节点非常困难,这是可能的,但需要额外的工作。如果使用嵌套集模型,选择子节点或所有节点,甚至查找所有节点的深度都可以在单个 SQL 查询中完成。
我希望这能让您了解如何解决您的问题,如果您在项目开发方面还很年轻,那么现在切换将为您省去很多麻烦。
Nested Set Model instead of Adjacency List Model
Can I suggest that you store your nodes in your database under NSM instead of ALM?
Notice that with ALM, (which is what you are using) getting the children nodes is quite difficult, its possible, but requires extra work. If you use nested set model selecting a child node, or all nodes, or even finding the depth of all nodes can be done in a single SQL query.
I hope this sheds some light on how you could solve your problem, if you are still young in the development of your project switching now will save you a lot of headaches later.