我有sql结构
id parent_id
1 0
2 1
3 2
4 3
5 4
6 5
7 1
8 7
9 8
我想使用php
调用id = 1的所有子子节点到第n个子节点我怎样才能得到它。我是使用php回调函数构建的。
答案 0 :(得分:0)
通过使用递归,你可以......
<?php
$arrayParent = $this->ToDatabase->("SELECT * FROM table WHERE parent_id = 0");
BuildList($arrayParent, 0);
function BuildList($arrayElements, $depth)
{
foreach($arrayElements as $element)
{
echo str_repeat(" ", $depth) . $element["id"];
$depth++;
$totalUnder = $this->ToDatabase->("SELECT * FROM table
WHERE parent_id = " . (int)$element["id"]);
if(count($totalUnder) > 0)
$depth = BuildList($totalUnder, $depth); //$totalUnder fetch to array and step deeper...
return $depth;
}
}
?>