PHP Array to List

Mazatec picture Mazatec · Nov 28, 2009 · Viewed 29.7k times · Source

How do I go from this multidimensional array:

Array (
  [Camden Town] => Array (
    [0] => La Dominican
    [1] => A Lounge
  ), 
  [Coastal] => Array (
    [0] => Royal Hotel
  ), 
  [Como] => Array (
    [0] => Casa Producto 
    [1] => Casa Wow
  ), 
  [Florence] => Array (
    [0] => Florenciana Hotel
  )
)

to this:

<ul>
  <li>Camden Town</li>
  <ul>
    <li>La Dominican</li>
    <li>A Lounge</li>
  </ul>
  <li>Coastal</li>
  <ul>
    <li>Royal Hotel</li>
  </ul>
  ...
</ul>

above is in html...

Answer

acmol picture acmol · Feb 4, 2012
//code by acmol
function array2ul($array) {
    $out = "<ul>";
    foreach($array as $key => $elem){
        if(!is_array($elem)){
                $out .= "<li><span>$key:[$elem]</span></li>";
        }
        else $out .= "<li><span>$key</span>".array2ul($elem)."</li>";
    }
    $out .= "</ul>";
    return $out; 
}

I think you are looking for this.