Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the array below which I would like to output in a specific HTML list format.

My PHP array is as follow:

Array
(
    [MAIN] => Master Product
    [ID1] => Array
        (
            [0] => Product 1
        )

    [ID2] => Array
        (
            [0] => Product 2
            [ID3] => Array
                (
                    [0] => Product 3
                )

            [ID4] => Array
                (
                    [0] => Product 4
                )
        )
)

The HTML list format I am looking for is as follows.

<ul id="treeview">
    <li>Master Product
        <ul>
            <li>Product 1</li>
            <li>Product 2
                <ul>
                    <li>Product 3</li>
                    <li>Product 4</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Any help would be appreciated.

share|improve this question
4  
What have you tried so far? –  Alex Mar 3 '12 at 1:36

2 Answers 2

up vote 3 down vote accepted

Try this on for size:


function recurseTree($var){
  $out = '<li>';
  foreach($var as $v){
    if(is_array($v)){
      $out .= '<ul>'.recurseTree($v).'</ul>';
    }else{
      $out .= $v;
    }
  }
  return $out.'</li>';
}

echo '<ul>'.recurseTree($yourDataArrayHere).'</ul>';

share|improve this answer
    
can you combine both this and mine to a self contained function? –  MyStream Mar 3 '12 at 2:08
    
Thanks for the reply. This is absolutely perfect and exactly what I was looking for. Much appreciated. –  hawx Mar 3 '12 at 23:13
$data = array(); // your data

function toUL($data=false){
 $response = '<ul>';
 if(false !== $data) {
   foreach($data as $key=>$val) {
    $response.= '<li>';
    if(!is_array($val)) {
     $response.= $val;
    } else {
     $response.= substr($response,0,strlen($response)-5) . toUL($val);
    }
    $response.= '</li>';
   }
 }
 $response.= '</ul>';
 return $response;
}

NOTE: untested - but a start?

share|improve this answer
    
key - missing $ –  Cheery Mar 3 '12 at 1:43
    
thank you =) - also added </li> removal –  MyStream Mar 3 '12 at 1:44
    
you might need a tokeniser around that substr() to check whether to do that based on if the previous iteration at the same level was a string or not..? –  MyStream Mar 3 '12 at 1:46
    
Sorry for late reply. This works perfectly. Thanks for the reply. –  hawx Mar 3 '12 at 23:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.