2012-08-03 101 views
0

可能重複多維數組:
How to create multi-dimensional array from a list?
PHP Create a Multidimensional Array from an array with relational data建築物的行集

目前,我有我的數據庫父子模型。該表是這樣的:

id   int 
parent_id int 
text  int 

假設我已經做了SELECT *查詢檢索這個表中的所有列,究竟我會去從這個結果集建立一個多維數組,每個數組,其中包含parent_id等於行id的子數組。

的樣本數據:

id parent_id text 
1  NULL  Blah1 
2  1   Blah 2 
3  2   Blah3 
4  1   Blah 4 

最後,一旦該數組建成後,你會如何遍歷它打印出來的樹像凹陷結構?

Blah1 
    Blah2 
     Blah3 
    Blah4 

您的幫助是最受讚賞的。

+0

見我的答案[這裏](http://stackoverflow.com/a/11497724/1446794) – 2012-08-03 08:29:19

回答

0

試試這個

$items = array(
    array('id' => 1, 'parent_id' => null, 'text'=>'text'), 
    array('id' => 2, 'parent_id' => 1 , 'text'=>'text'), 
    array('id' => 3, 'parent_id' => 2, 'text'=>'text'), 
    array('id' => 4, 'parent_id' => 1 , 'text'=>'text'), 
); 

$childs = array(); 

foreach($items as $item) 
    $childs[$item['parent_id']][] = $item; 

foreach($items as $item) if (isset($childs[$item['id']])) 
    $item['childs'] = $childs[$item['id']]; 

$tree = $childs[0]; 

var_dump($tree);