gpt4 book ai didi

php - 通过递归函数创建树

转载 作者:可可西里 更新时间:2023-11-01 07:09:10 26 4
gpt4 key购买 nike

我有一张 table

id,name,parent_id,designation 列,

我想在 php 中通过递归函数创建树。

每个 parent_id 都在 id 列中查找,如果用户登录,则用户可以根据 parent_id 查看自己和下面的所有记录。

喜欢

一个|乙|C|丁|乙|F

如果 A 用户登录,那么他可以查看所有 (A,B,C,D,E,F) 详细信息。如果 B 登录,则可以查看 (B,c,D,E,F) 等所有...如果F登录然后他只能看到自己的记录..感谢提前

最佳答案

创建函数 fetch_parent;

function fetch_parent($parent_id) {
$query = 'SELECT * FROM `my_table` WHERE `parent_id`='. $parent_id;
// use your own sql class/function whatever to retrieve the record and store it in variable $parent
if($parent->parent_id !== null) { // asuming a 'root' record will have null as it's parent id
fetch_parent($parent->parent_id); // here you go with your recursion
}
return;
}

然后只需使用您希望其父级的记录调用该函数:

$first_parent_id = 8;
fetch_parent($first_parent_id);

注意事项:

  • $parent var也可以是数组,具体取决于mysql结果集
  • 请检查 mysql 注入(inject)等查询中的 $parent_id。

关于php - 通过递归函数创建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12277829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com