这个问题是关于Kohana框架的。我是新手。
使用foreach()
我想显示一些数据。一切都很好,但我想将数据连续分组 4 个项目,因此它看起来像:
1st 2nd 3rd 4th
5th 6th 7th 8th
9th 10th 11th 12th
....
这就是为什么我必须每 4 次添加一次<div>
。
你是怎么做到的?您是否使用简单的计数器并检查其mod是否为零?是否有一个特殊的 Kohana 函数来检查 foreach() 中当前$item的数量是第一个、第二个还是第 n 个......项目?
<?foreach ($items as $item): ?>
//add <div> tag for 1st, 4th, 7th, etc item
//do something
//add closing </div> tag for 1st, 4th, 7th, etc item
<? endforeach; ?>
使用通过$key => $item
指定数组键的foreach
构造,您可以测试是否$key % 4 == 0
(或者在您的情况下可能是$key % 4 == 3
)关闭打开的<div>
。
// Initial opening div..
<div>
<?foreach ($items as $key => $item): ?>
<?=$item ?>
<? if ($key % 4 == 3): ?>
... Close the open div and open a new one
</div>
<div>
<? endif; ?>
<? endforeach; ?>
</div>
模板语法伤害了我的眼睛。这是正确的 PHP:
echo '<div>';
foreach ($items as $key => $item) {
echo $item;
if ($key % 4 == 3) {
echo '</div><div>';
}
}
echo '</div>';
给定以下输入:
$items = array('a','b','c','d','e','f','g','h','i','j','k');
// Output:
<div>abcd</div><div>efgh</div><div>ijk</div>