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 關注
- 229 瀏覽
添加回答
舉報