我有一个未知长度的数组:
$array = array('1', '2', '3', '4', '5', '6', '7', '8' ...);
Run Code Online (Sandbox Code Playgroud)
我需要将此数组输出为多个列表,其中为每3个数组条目创建一个新列表.
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>7</li>
<li>8</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
请注意,即使它不包含3个列表项,我也需要关闭最后一个列表.
这是我的尝试:
<?php for ($i = 0; $i < count($rows); ++$i): ?>
<?php if (($i % 3) == 0): ?>
<ul>
<?php endif; ?>
<li><?php print $rows[$i]; ?></li>
<?php if (($i % 3) == 2): ?>
</ul>
<?php endif; ?>
<?php endfor; ?>
Run Code Online (Sandbox Code Playgroud)
你可以利用一个array_chunk来完成这个任务.他们三个人:
$array = range(1, 8);
$unknown_length = array_chunk($array, 3); // cut by batches of three
foreach($unknown_length as $ul) {
echo '<ul>';
foreach($ul as $li) {
echo "<li>$li</li>";
}
echo '</ul>';
}
Run Code Online (Sandbox Code Playgroud)