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.

1
  • See my answer here Commented Aug 3, 2012 at 8:29

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.