2013-03-05 68 views
1

我有SQL結構父子關係的船最多n個子

id parent_id 
1  0 
2  1 
3  2 
4  3 
5  4 
6  5 
7  1 
8  7 
9  8 

我想要使用呼叫ID的所有子子= 1到n個子節點PHP

我怎樣才能得到它。我是通過使用PHP回調函數結構。

+0

看看[這裏](http://stackoverflow.com/questions/12948009/finding-all-parents-in-mysql-table與單一查詢)在我的問題和答案給出。不要忘記看到架構 – 2013-03-05 11:19:36

回答

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("&nbsp;&nbsp;", $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; 
    } 
} 
?> 
+0

保重,它是非常消費SQL請求 – MatRt 2013-03-05 11:03:38

+0

這是正確的,但是,這是一個可能的解決方案。通過優化第一個查詢,您可以通過添加一個計數或在parent_id下保存一些元素來減少請求... – 2013-03-05 14:37:57