创建一个函数 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;
}
Run Code Online (Sandbox Code Playgroud)
然后只需使用您想要其父级的记录调用该函数即可:
$first_parent_id = 8;
fetch_parent($first_parent_id);
Run Code Online (Sandbox Code Playgroud)
笔记: