views:

815

answers:

2

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>
Camden Town
  La Dominican
  A Lounge
Coastal
  Royal Hotel
etc.....

above is in html...

Thanks!

A: 

Assume your data is in $array.

print '<ul>';
foreach ($array as $city => $hotels)
{
    print "<li>$city</li>\n<ul>\n";
    foreach ($hotels as $hotel);
    {
        print "    <li>$hotel</li>\n";
    }
    print "</ul>\n\n";
}
print '</ul>';

Haven't tested it, but I'm pretty sure it's right.

Francis Rath
This isn't quite what was requested, but it is probably what was intended. Some CSS will complete the formatting.
Ewan Todd
actually the above code only provides one "child" for each parent, so for example Camden Town is only given one hotel listed instead of 2.
Ashley Ward
+1  A: 

Here's a much more maintainable way to do it than to echo html...

<ul>
    <?php foreach( $array as $city => $hotels ): ?>
    <li><?= $city ?>
     <ul>
      <?php foreach( $hotels as $hotel ): ?>
      <li><?= $hotel ?></li>
      <?php endforeach; ?>
     </ul>
    </li>
    <?php endforeach; ?>
</ul>

Here's another way using h2s for the cities and not nested lists

<?php foreach( $array as $city => $hotels ): ?>
<h2><?= $city ?></h2>
    <ul>
     <?php foreach( $hotels as $hotel ): ?>
     <li><?= $hotel ?></li>
     <?php endforeach; ?>
    </ul>
<?php endforeach; ?>

The outputted html isn't in the prettiest format but you can fix that. It's all about whether you want pretty html or easier to read code. I'm all for easier to read code =)

Galen
this is the correct answer. Perfect. Thanks for introducing me to endforeach. this is EXACTLY what I have been looking for.
Ashley Ward