Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PHP array in HTML list

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.

like image 479
hawx Avatar asked Jan 17 '23 08:01

hawx


2 Answers

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

like image 111
Justin Pearce Avatar answered Jan 20 '23 15:01

Justin Pearce


$data = array(); // your data

function toUL($data=false, $flatten=false){
 $response = '<ul>';
 if(false !== $data) {
   foreach($data as $key=>$val) {
    $response.= '<li>';
    if(!is_array($val)) {
     $response.= $val;
    } else {
     if(!$flatten){
       $response.= toUL($val);
     } else {
       // pulls the sub array into the current list context
       $response.= substr($response,0,strlen($response)-5) . toUL($val);
     }
    }
    $response.= '</li>';
   }
 }
 $response.= '</ul>';
 return $response;
}

// Test #1 -- named values echo toUL(array('a'=>'b','c'=>'d','e'=>array('f'=>'g'))); // Result #1

  • b
  • d
    • g

// Test #2 -- value lists echo toUL(array('a','b','c',array('d','e','f'))); // Result #2

  • a
  • b
  • c
    • d
    • e
    • f
like image 28
MyStream Avatar answered Jan 20 '23 15:01

MyStream