假设我们有一个数组:
$aa = array('student1'=>array(1,2,3),'student2'=>array(3,2,4),'student3'=>array(4,3,5));
我希望得到如下的HTML输出:
<ul>
<li>student1
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
</li>
<li>student2
<ul>
<li>3</li>
<li>2</li>
<li>4</li>
</ul>
</li>
<li>student3
<ul>
<li>4</li>
<li>3</li>
<li>5</li>
</ul>
</li>
</ul>
但我所能做的只是
<ul>
<li>
<ul>
<li>1</li>
<li>1</li>
<li>1</li>
</ul>
</li>
<li>
<ul>
<li>3</li>
<li>2</li>
<li>4</li>
</ul>
</li>
<li>
<ul>
<li>4</li>
<li>3</li>
<li>5</li>
</ul>
</li>
</ul>
换句话说,我无法为每个内部数组打印键。怎么做?
我编写了类似的东西:
echo '<ul>';
foreach($aa as $a)
{
echo '<li>' . /*Here it should be written the current student name*/ '<ul>';
foreach($a as $b)
{
echo '<li>' . $b . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
答案 0 :(得分:4)
<ul>
<?php
foreach ($aa as $name => $values) {
echo "<li>$name\n";
echo "<ul>\n";
foreach ($values as $value) {
echo "<li>$value</li>\n";
}
echo "</ul>\n";
echo "</li>\n";
}
?>
</ul>
答案 1 :(得分:0)
按如下方式打印数组:
echo "<pre>";
print_r($array);
echo "</pre>";
通过这种方式,您可以查看数组的内部结构。
然后你可以这样列出:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}