我正在尝试遍历多维数组。每个数组的子数组都有不同数量的值。我将如何循环浏览以输出每辆汽车的价值的列表项?
$cars = array (
array("Volvo",1,2,3),
array("BMW",4,5),
array("Saab",6,7,8,9),
array("Land Rover",10),
);
$carsLength = count($cars);
for ($row = 0; $row < $carsLength; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
$listLength = count($bullet);
for ($bullet = 0; $bullet < $listLength; $bullet++) {
echo "<li>".$cars[$row][$bullet]."</li>";
}
echo "</ul>";
}
答案 0 :(得分:1)
您需要不需要任何索引维护,
foreach ($cars as $key => $value) {
echo "<p><b>Row number $key</b></p>";
echo "<ul>";
foreach ($value as $value1) {
echo "<li>" . $value1 . "</li>";
}
echo "</ul>";
}
答案 1 :(得分:1)
仅需foreach和爆破即可进一步简化代码。
Implode通过一个介于数组之间的“胶水”来创建字符串。
$cars = array (
array("Volvo",1,2,3),
array("BMW",4,5),
array("Saab",6,7,8,9),
array("Land Rover",10),
);
foreach($cars as $row => $sub){
echo "<p><b>Row number " . ($row +1) . "</b></p>\n";
echo "<ul>\n";
echo "<li>" . implode("</li><li>", $sub) . "</li>\n";
echo "</ul>\n\n";
}
输出:
<p><b>Row number 1</b></p>
<ul>
<li>Volvo</li><li>1</li><li>2</li><li>3</li>
</ul>
<p><b>Row number 2</b></p>
<ul>
<li>BMW</li><li>4</li><li>5</li>
</ul>
<p><b>Row number 3</b></p>
<ul>
<li>Saab</li><li>6</li><li>7</li><li>8</li><li>9</li>
</ul>
<p><b>Row number 4</b></p>
<ul>
<li>Land Rover</li><li>10</li>
</ul>