0

I have this table in my DB (I hope it's correctly showed):

+++++++++++++++++++++++++++
| id_child |--| id_parent |
+++++++++++++++++++++++++++
|    5     |--|     2     |
|    6     |--|     2     |
|    7     |--|     4     |
|    8     |--|     4     |
|    9     |--|     5     |
|    10    |--|     5     |
|    11    |--|     9     |
|    12    |--|     9     |
---------------------------

I wrote a php recursive function that create a multidimensional array from a parent passed (in this case '2'). So, if I put a print_r I obtain this result:

Array ( [5] => Array ( [9] => Array ( [11] => Array ( ) [12] => Array ( ) ) [10] => Array ( ) ) [6] => Array ( ) )

How I can obtain a structure of this type? (I exclude the first parent, 2)

(2)
-5
--9
----11
----12
--10
-6

Thanks.

3
  • (at)klkvsk, (at)Eugene Rieck: your solutions perfectly work. Is there a better solution than an array to quickly obtain the parent of a child and the children of a parent? Commented Aug 1, 2013 at 16:01
  • E.g.: if I want to obtain children of parent=9 (11 and 12), is there a simple way? I think my array will be changed Commented Aug 1, 2013 at 16:07
  • Just start your recursive function at ID=9 and generate the new array from there Commented Aug 1, 2013 at 18:23

2 Answers 2

1

You would need another recursive function to iterate over your array, like so:

function printCategories($categories, $level = 1) {                                
    foreach ($categories as $cat => $subCats) {                                    
        echo str_repeat('-', $level) . $cat . "\n";                                
        printCategories($subCats, $level+1);                                       
    }                                                                              
}                                                                                  
printCategories($categories);    
Sign up to request clarification or add additional context in comments.

Comments

1
<?php

function printtree($tree, $level) {
  $prefix=str_repeat('-',$level);
  foreach ($tree as $k=>$v) {
    echo "$prefix$k<br>\n";
    if (is_array($v)) if (sizeof($v)>0) printtree($v,$level+1);
   }
}

$tree=array( 5=>array(9=>array(11=>array(), 12=>array()), 10=>array()), 6=>array());
printtree($tree,1);

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.