2012-08-03 95 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);