PHP数组列表

Ash*_*Ash 7 html php arrays html-lists unordered

我如何从这个多维数组:

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
  )
)
Run Code Online (Sandbox Code Playgroud)

对此:

<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>
Run Code Online (Sandbox Code Playgroud)

上面是html ...

小智 22

//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; 
}
Run Code Online (Sandbox Code Playgroud)

我想你正在寻找这个.

  • Rockstar代码就在这里.谢谢你为我节省了建造它的时间! (3认同)

Gal*_*len 14

这是一种更易于维护的方法,而不是回显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>
Run Code Online (Sandbox Code Playgroud)

这是使用h2s进行城市而不是嵌套列表的另一种方式

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

输出的html不是最漂亮的格式,但你可以修复它.这是关于你是否想要漂亮的HTML或更容易阅读代码.我都是为了更容易阅读代码=)


ya.*_*eck 7

重构acmol的功能

/**
 * 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>';
}
Run Code Online (Sandbox Code Playgroud)