Ash Ash - 7 months ago 24
PHP Question

PHP Array to List

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

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 =)

Comments