PHP array to list

How to 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 ) ) 

:

 <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 ...

+7
arrays html php html-lists unordered
source share
5 answers

Here's a much more convenient way to do this than the html echo ...

 <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 to use h2s for cities and non-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 output html is not in the best format, but you can fix it. It's all about whether you want pretty html or easier to read code. It's easier for me to read the code =)

+14
source share
 //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.

+21
source share

Refactored acmol funciton

 /** * Converts a multi-level array to UL list. */ function array2ul($array) { $output = '<ul>'; foreach ($array as $key => $value) { $function = is_array($value) ? __FUNCTION__ : 'htmlspecialchars'; $output .= '<li><b>' . $key . ':</b> <i>' . $function($value) . '</i></li>'; } return $output . '</ul>'; } 
+7
source share

Suppose your data is in an $ array.

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

Not tested, but I'm sure it is correct.

0
source share

You can do this with a display instead of a loop (as in other answers):

 $list = ['Orange', 'Apple', 'Banana']; $numbered_list = true; $list_type = $numbered_list ? 'o' : 'u'; echo "<" . $list_type . "l>\n" . implode("\n", array_map(function ($item) {return '<li>' . $item . '</li>';}, $list)) . "\n</" . $list_type . "l>"; 
0
source share

All Articles