0

Possible Duplicate:
How to create multi-dimensional array from a list?
PHP Create a Multidimensional Array from an array with relational data

I currently have a parent-child model in my database. The table looks like this:

id         int  
parent_id  int
text       int

Assuming I've done the SELECT * query to retrieve all the columns on this table, how exactly would I go about building a multi-dimensional array from this result set, where each array contains an array of children where the parent_id is equal to the rows id.

Sample data:

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

Finally, once that array is built, how would you iterate through it to print out the tree like indented structure?

Blah1 
    Blah2
        Blah3
    Blah4

Your help is most appreciated.

Community
  • 1
  • 1
Sinmok
  • 656
  • 1
  • 10
  • 19

1 Answers1

0

try this

$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);
voodoo417
  • 11,861
  • 3
  • 36
  • 40