Tab
Tab

Reputation: 309

create a subcategories hierarchy from multidimensional array

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.

Upvotes: 0

Views: 315

Answers (2)

Eugen Rieck
Eugen Rieck

Reputation: 65264

<?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);

?>

Upvotes: 1

klkvsk
klkvsk

Reputation: 670

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);    

Upvotes: 1

Related Questions