要列出的 PHP 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1813098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Array to List
提问by Mazatec
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...
上面是html...
回答by acmol
//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.
我想你正在寻找这个。
回答by Galen
Here's a much more maintainable way to do it than to echo html...
这是一种比 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
这是对城市使用 h2s 而不是嵌套列表的另一种方法
<?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 =)
输出的 html 不是最漂亮的格式,但您可以修复它。这完全取决于您是否想要漂亮的 html 或更易于阅读的代码。我都是为了更容易阅读代码 =)
回答by ya.teck
Refactored acmol's funciton
重构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>';
}
回答by Francis Rath
Assume your data is in $array.
假设您的数据在 $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>';
Haven't tested it, but I'm pretty sure it's right.
还没有测试过,但我很确定它是正确的。

