如何将类添加到最后一个表行

时间:2012-12-16 02:09:35

标签: php

我想为主要类别的每个<tr>添加一个类。我不想将类名添加到每个<tr>。我的剧本可以改变什么?

像这样:

    <table>
    <tr>
    <th></th>
    </tr>
    <tr>
    <td></td>
    </tr>
    <tr class="test">
    <td></td>
    </tr>

<th></th>
<tr>
<td></td>
</tr>
<tr class="test">
    <td></td>
    </tr>
</table>


 <table class="data forum">   

        <? foreach ($this->mainCategories as $mainCategory): ?>
            <tr>
                <th><strong><?= $this->escape($mainCategory->fcName) ?></strong></th>
                <th>&nbsp;</th>
                <th><strong>Topics</strong></th>
                <th><strong>Laatste topic</strong></th>
             </tr>
             <? foreach ($mainCategory->getSubCategories() as $category): ?>

                <tr>
                    <td><a href="<?= $this->url(array('categoryid' =>  $this->escape($category->getID()), 'controller' => 'forum', 'action' => 'subcategory'), 'default', true) ?>"><?= $this->escape($category->getName()) ?></a></td>
                    <td><?= $this->escape($category->fcDescription) ?></td>
                    <? if ($this->escape($category->numTopics) > 0): ?>
                        <td><?= $this->escape($category->numTopics) ?></td>
                        <td><?= date_create($this->escape($category->last_topic))->format('d-m-Y H:i') ?></td>
                    <? else: ?>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    <? endif ?>
                </tr>
             <? endforeach ?>
            <tr>
                <td class="split"></td>
            </tr>

         <? endforeach ?>

 </table>

1 个答案:

答案 0 :(得分:1)

抓住count变量的$this->mainCategories并针对计数器变量测试最后一个...

$count = count($this->mainCategories;
$current = 0;

<?
    foreach ($this->mainCategories as $mainCategory):
        $current++;
?>
    <tr<?= $current == $count?' class="someClass"':''?>>

<强>更新

让我们看一个简化版本作为概念证明:

<?php
$mainCategories = array("Eins", "Zwei", "Drei");

$count = count($mainCategories);
$current = 0;

    foreach ($mainCategories as $mainCategory):
    $current++;
?>
    <tr<?= $current == $count?' class="someClass"':''?>>
        <td><?= $mainCategory ?></td>
    </tr>
<?php endforeach ?>

这会生成以下HTML:

<tr>
    <td>Eins</td>
</tr>
<tr>
    <td>Zwei</td>
</tr>
<tr class="someClass">
   <td>Drei</td>
</tr>