Dipesh Shihora
Dipesh Shihora

Reputation: 424

Prepare Tree in php

I'm having following array.

Array
(
[a] => Array
    (
        [d] => Array
            (
                [f] => Array
                    (
                    )

                [g] => Array
                    (
                        [h] => Array
                            (
                            )

                        [i] => Array
                            (
                            )

                    )

                [j] => Array
                    (
                    )

            )

        [e] => Array
            (
            )

    )

[b] => Array
    (
    )

[c] => Array
    (
    )

)

I have tried with below code but not getting required output.

str($treeArr);

 function str($arr){
    foreach($arr as $key=>$value){
        if(!empty($value)){
            echo $key.">";
            str($value);
        }
        else{
            echo $key."<br>";
        }
    }
}

I need following output.

a>d>f
a>d>g>h
a>d>g>i
a>d>j
a>e
b
c

Upvotes: 1

Views: 69

Answers (1)

sis
sis

Reputation: 68

Hi guys,is this what you want?

$a=array('a'=>array('d'=>array('f'=>array(),
                               'g'=>array('h'=>array(),
                                          'i'=>array()),
                               'j'=>array()),
                    'e'=>array()),
         'b'=>array(),
         'c'=>array()
);                                                                                                                       
str($a);
function str($arr){
   static $temp=array();
   foreach($arr as $k=>$v){
      $temp[]=$k;  
      if(!empty($v)){
         str($v);
      }else{
         $str=implode(">",$temp);
         echo $str."\n";
      }  
      array_pop($temp);
   }  
}

output:

a>d>f 
a>d>g>h
a>d>g>i
a>d>j
a>e
b
c

Upvotes: 1

Related Questions