我将数据存储在一个数组中($ rows)。 为了读取数组并使用foreach函数创建一个dinamic表。
<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元素的类。 我怎么能这样做? 感谢
答案 0 :(得分: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>";
}
此方法也适用于多维数组。
修改即可。正如注释中所指出的,如果数组中的某些值重复(使用最后一个),则此方法可能会触发错误的最终结果。正确的防弹版应该是:
foreach ($rows as $key => $row) {
$end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';
// ...
答案 1 :(得分: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应该是一个未使用的变量。
答案 2 :(得分: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>";
}
答案 3 :(得分: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>";
}