Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a multidimensional array keys in tree format in PHP?

How can I return multidimensional array keys in tree format in PHP?

For example, if I have the following array:

$array = array ( 
    array (
        'name' => 'A', 
        'product' => array (
            'qty' => 1,
            'brand' => 'Tim'
        ), 
        'goods' => array (
            'qty' => 2
        ), 
        'brand' => 'Lin'
    ),
    array (
        'name' => 'B', 
        'product' => array (
            'qty' => 6,
            'brand' => 'Coff'
        ),
        'goods' => array (
            'qty' => 4
        ), 
        'brand' => 'Ji'
    )
);

How can I get a result like the following -- including no repeating of keys:

-name
-product
--qty
--brand
-goods
--qty
--brand
like image 790
aje Avatar asked Aug 28 '26 04:08

aje


1 Answers

Recursive functions should cover any depth you want/need:

 function print_tree($tree, $level = 0) {
     foreach($tree AS $name => $node) {
         if(
               is_scalar($node) OR
               (
                   is_object($node) AND
                   method_exists($node, '__toString')
               )
           ) {
             echo str_repeat('-', $level).$name.': '.$node;
         }
         else if(
                   is_array($node) OR
                   (
                       is_object($node) AND
                       $node InstanceOf Traversable
                   )
                ) {
             echo str_repeat('-', $level).$name.":\n";
             print_tree($node, $level+1);
         }
     }
 }
like image 189
Mihai Stancu Avatar answered Aug 29 '26 20:08

Mihai Stancu