CodeIgniter中的最后一个循环foreach
我试图捕获CodeIgniter for循环中的最后一个循环。我试图在每个新闻项目下产生一个< hr />,但最后一项。这是我的代码:CodeIgniter中的最后一个循环foreach
<table class="news">
<?php foreach($news as $news_item): ?>
<tr>
<td class="headline"><?php echo $news_item['title']; ?></td>
</tr>
<tr>
<td class="text"><?php echo $news_item['text']; ?></td>
</tr>
<tr>
<td><hr /></td>
</tr>
<?php endforeach; ?>
</table>
Уou可以尝试这样的事:
<?php for($i = 0, $lastIDX = count($news)-1; $i<=$lastIDX; $i++): ?>
<!-- html code ... $news_item is $news[$i] now -->
<? if ($i !== $lastIDX) : ?>
<tr>
<td><hr /></td>
</tr>
<?php endif; ?>
<?php endfor; ?>
但它会更好地使用CSS:最后一子选择。
这是怎么做的CSS选择器呢? :-)在每个HR和 上添加class =“hr”.news .hr:last-child { display:none; }作为CSS不工作 –
忘记hr并使用border-bottom:solid 1px#000;使用填充添加一些距离 – allen213
获取数组的最后一个关键事前,并比较其当前的一个,而循环:
$keys = array_keys($news);
$last_key = end($keys);
foreach ($news as $news_key => $news_item) {
if ($news_key == $last_key) {
// at the last item
} else {
// not at the last item
}
}
而且你可以指望你的数组中的元素事前,并有在每一轮增加的循环内计数器,所以你可以告诉你是否在最后。
你可以用这个作为一个解决方案:
$last = end($news);
<table class="news">
<?php foreach($news as $news_item): ?>
<tr>
<td class="headline"><?php echo $news_item['title']; ?></td>
</tr>
<tr>
<td class="text"><?php echo $news_item['text']; ?></td>
</tr>
<tr>
<td><?=(($last == $news_item)?"":"<hr />")?></td>
</tr>
<?php endforeach; ?>
</table>
凡$最后是你的阵列XD的最后一个阵列。
这是你的问题吗?是不是工作或其他.. –