2 回答
TA贡献1802条经验 获得超5个赞
因为你希望每个排须是一个新的表列,你会希望把在foreach内部的<td>
,而不是<tr>
。
此外,如果您已经du_head
从查询中获取信息,则您可能不需要在 foreach 中执行该查询。duh_isi
如果是同一个表的一部分,您可以只添加到选择中,或者如果不只是进行连接。
此外,您应该使用 PHP 框架。这将允许您将数据库查询逻辑与 html 模板逻辑分开,并提供一个 ORM 来清理您的数据库输入,这两者都是安全和可维护代码的关键。
TA贡献1810条经验 获得超5个赞
您的列和行循环逻辑混淆了,首先尝试将其映射到数组中:
$rows = [];
$additional_column = count($du_head); // count the columns to get the last column index for displaying the delete button
foreach ($du_head as $colkey => $value) {
$q = $this->db->query("select * from data_umum where duh_id = '$value->duh_id'")->result();
foreach ($q as $rowkey => $ac) {
$rows[$rowkey][$colkey] = "<td>" . $ac->duh_isi . "</td>";
}
$rows[$colkey][$additional_column] = "<td>" . $ac->duh_isi . "</td>";
}
然后你可以foreach再次循环显示行:
foreach ($rows as $rowkey => $row) {
echo "<tr>"; // print each table row
foreach ($row as $colkey => $col) {
echo $col; // print each table column
}
echo "<td><i class='fa fa-trash'><a href='" . site_url("controller/delete/$rowkey") . "'></a></i></td>"; // print each delete button, adjust it to whatever you need
echo "</tr>\r\n";
}
把它放在一起,它会像:
<table class="table table-striped table-bordered zero-configuration">
<thead>
<tr>
<?php
foreach ($du_head as $key => $value) {
echo "<th>" . $value->duh_judul . "</th>";
}
?>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
$rows = [];
$additional_column = count($du_head); // count the column total to get the last column index for displaying the delete button
foreach ($du_head as $colkey => $value) {
$q = $this->db->query("select * from data_umum where duh_id = '$value->duh_id'")->result();
foreach ($q as $rowkey => $ac) {
$rows[$rowkey][$colkey] = "<td>" . $ac->duh_isi . "</td>";
}
$rows[$colkey][$additional_column] = "<td>" . $ac->duh_isi . "</td>";
}
foreach ($rows as $rowkey => $row) {
echo "<tr>"; // print each table row
foreach ($row as $colkey => $col) {
echo $col; // print each table column
}
echo "<td><i class='fa fa-trash'><a href='" . site_url("controller/delete/$rowkey") . "'></a></i></td>"; // print each delete button, adjust it to whatever you need
echo "</tr>\r\n";
}
?>
</tbody>
</table>
但这绝对很奇怪,因为您在循环内和模板视图内混合了查询,您应该考虑使用 PHP 框架来防止进一步的挫折。
- 2 回答
- 0 关注
- 194 浏览
添加回答
举报