0

我将数据存储在一个数组($rows)中。为了读取数组并生成一个动态表,我使用 foreach 函数。

<table>

    foreach ($rows as $row) {
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
    }

</table>

我的目标是找到数组的最后一个值(末尾),以便为显示的最后一行更改 TR 元素的类。我怎么能这样做?谢谢

4

4 回答 4

1

试试这个:

foreach ($rows as $key => $row) {
    $end = end($rows) === $row ? 'class="last"' : '';
    echo "<tr $end>";
    echo "<td>" . $row['field1'] . "</td>";
    echo "<td>" . $row['field2'] . "</td>";
    echo "<td>" . $row['filed3'] . "</td>";
    echo "</tr>"; 
}

此方法也适用于多维数组。

http://codepad.org/HQG9ytBX

编辑. 正如评论中所指出的,如果数组中的某些值重复(最后一个),这种方法可能会触发错误的最终结果。正确的防弹版本应该是:

foreach ($rows as $key => $row) {
    $end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';

    // ...
于 2013-03-16T12:26:52.507 回答
1
foreach ($rows as $row) {
$is_last_row = ++$i == count($rows);
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
    }

这里 $i 应该是一个未使用的变量。

于 2013-03-16T12:27:45.270 回答
0

试试这个

$numItems = count($rows);
$i = 0;
foreach($rows as $row) {

$trClass = 'firstclass';
if(++$i === $numItems) 
{
$trClass = 'lastclass';
}


echo "<tr class='$trclass'>";
    echo "<td>" . $row['field1'] . "</td>";
    echo "<td>" . $row['field2'] . "</td>";
    echo "<td>" . $row['filed3'] . "</td>";
    echo "</tr>"; 
}  
于 2013-03-16T12:36:50.020 回答
0
// first, let's find out the last key
end($rows);
$last = key($rows);

// then just loop over
foreach ($rows as $key => $row) {
        if ($key == $last) {
            // last leaf of the summer...
        }
        echo "<tr>";
        echo "<td>" . $row['field1'] . "</td>";
        echo "<td>" . $row['field2'] . "</td>";
        echo "<td>" . $row['filed3'] . "</td>";
        echo "</tr>"; 
}
于 2013-03-16T12:39:07.577 回答