hawx
hawx

Reputation: 1669

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.

Upvotes: 4

Views: 7863

Answers (3)

Gautier
Gautier

Reputation: 1146

Inspired from this answer but where leaves are surounded by <li>

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

    return $out;
}

And if you have associative array you can try this function:

function recurseTree($var)
{       
    $out = '';
    foreach($var as $k => $v){
        if (is_array($v)) {
            $out .= '<dl>'.self::recurseTree($v).'</dl>';
        } else {
            $out .= '<dt>'.$k.'</dt>'.'<dd>'.$v.'</dd>';
        }
    }

    return $out;
}

Upvotes: 0

MyStream
MyStream

Reputation: 2553

$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

Upvotes: 4

Justin Pearce
Justin Pearce

Reputation: 5097

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

Upvotes: 5

Related Questions