2012-11-16 123 views
0

我試圖捕獲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> 
+0

這是你的問題嗎?是不是工作或其他.. –

回答

1

У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:最後一子選擇。

+0

這是怎麼做的CSS選擇器呢? :-)在每個HR​​和 上添加class =「hr」.news .hr:last-child { display:none; }作爲CSS不工作 –

+0

忘記hr並使用border-bottom:solid 1px#000;使用填充添加一些距離 – allen213

0

獲取數組的最後一個關鍵事前,並比較其當前的一個,而循環:

$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 
    } 
} 

而且你可以指望你的數組中的元素事前,並有在每一輪增加的循環內計數器,所以你可以告訴你是否在最後。

0

你可以用這個作爲一個解決方案:

$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的最後一個陣列。

相關問題