简体   繁体   English

通过递归函数创建树

[英]create tree through recursive function

I have a table 我有一张桌子

id,name,parent_id,designation columns, id,name,parent_id,designation列,

i want create tree through recursive function in php. 我想通过PHP中的递归函数创建树。

every parent_id is looking in id column and if user login then user can see own and all below records according parent_id . 每个parent_id都在id列中查找,如果用户登录,则用户可以根据parent_id查看自己和所有以下记录。

like 喜欢

A | A | B | B | c | c | D | D | E | E | F F

if A user login then he can all(A,B,C,D,E,F) details.and if B login then see (B,c,D,E,F) and like all... if F login then he can see only own records.. Thanks for advance 如果一个用户登录,那么他可以全部(A,B,C,D,E,F)详细信息。如果B登录然后看到(B,c,D,E,F)和所有...如果F登录然后他只能看到自己的记录..感谢您的进步

create a function fetch_parent; 创建一个函数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;
}

Then just call the function with the record you want it's parents from: 然后只需使用您希望它的父母来自的记录调用该函数:

$first_parent_id = 8;
fetch_parent($first_parent_id);

Notes: 笔记:

  • the $parent var can also be an array, depending on the mysql result set $ parent var也可以是一个数组,具体取决于mysql结果集
  • PLEASE PLEASE PLEASE check $parent_id in the query for mysql injection etc. 请您在查询mysql注入等检查$ parent_id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM