简体   繁体   中英

create tree through recursive function

I have a table

id,name,parent_id,designation columns,

i want create tree through recursive function in 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 .

like

A | B | c | D | E | 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

create a function 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
  • PLEASE PLEASE PLEASE check $parent_id in the query for mysql injection etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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