我有一个基于 result() 的活动记录代码点火器。 结果有 28 条记录 我的意思是创建一个基于此记录的表。 我的问题是,我想制作 7 行、4 列以提高可读性。 我的代码是这样的:
<td colspan="4">
<?php
foreach ($damage_codes as $row) {
// Create a column. <td>
// create a row <tr>
// When this column have four row, create a next column again.
// So on, so on
echo . $row->DAMAGE_ID . " " . $row->NAMA_DAMAGE ;
}
?>
</td>
我必须管理它,但不适合我自己的报告。 这是我现在的代码
<?php
$i = 0;
foreach ($damage_codes as $row) : ?>
<?= ($i % 4 == 0) ? "<tr>" : false; ?>
<?= "<td>[".$row->DAMAGE_ID . "]" . $row->NAMA_DAMAGE . "</td>"; ?>
<?php
$i++;
endforeach;
echo "</tr>"?>
输出如下:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 |
如何,我可以这样做吗:
| 1 | 5 | 9 | 13 |
| 2 | 6 | 10 | 14 |
| 3 | 7 | 11 | 15 |
| 4 | 8 | 12 | 16 |
任何帮助,非常感谢
只需在 foreach 循环之外使用计数器变量来跟上它。
类似这样的:
<table>
<?php
$i = 0;
foreach ($damage_codes->result() as $row):
?>
<?= ($i % 4 == 0) ? "<tr>" : false; ?>
<?= "<td>".$row->DAMAGE_ID . " " . $row->NAMA_DAMAGE . "</td>;
<?= ($i % 4 == 0) ? </tr>" : false; ?>
<?php
$i++;
endforeach;
?>
</table>
也许这会对你有一点帮助
更新版本:
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
$md_arr = array();
$cols = 4;
$i = 0;
$col = 0;
$row = 0;
// first convert your single array to a multidimensional one
foreach ($arr as $k=>$v) {
$i++;
$md_arr[$row][$col] = $v;
$col++;
if( $i % $cols == 0 ){
$row++;
$col = 0;
}
}
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
// then transpose your new multi array
$md_arr = transpose( $md_arr );
// last render the table with the transposed array
echo "<table>";
foreach ($md_arr as $k=>$v) {
echo "<tr>";
foreach ($v as $kk=>$vv) {
echo "<td>";
echo $md_arr[ $k ][ $kk ];
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
虽然从技术上讲,在循环时手动管理索引会提高性能,并且因为您的结果将是已知的小尺寸,但我建议简单地分块,然后转置数据。创建一个库方法或辅助函数来执行此重组操作(它不属于控制器、模型或视图层),然后视图可以迭代完全准备好的有效负载。
代码:(演示)
$damage_codes = range(1, 28);
$result = array_map(null, ...array_chunk($damage_codes, 7));
var_export($result);
输出:
array (
0 =>
array (
0 => 1,
1 => 8,
2 => 15,
3 => 22,
),
1 =>
array (
0 => 2,
1 => 9,
2 => 16,
3 => 23,
),
2 =>
array (
0 => 3,
1 => 10,
2 => 17,
3 => 24,
),
3 =>
array (
0 => 4,
1 => 11,
2 => 18,
3 => 25,
),
4 =>
array (
0 => 5,
1 => 12,
2 => 19,
3 => 26,
),
5 =>
array (
0 => 6,
1 => 13,
2 => 20,
3 => 27,
),
6 =>
array (
0 => 7,
1 => 14,
2 => 21,
3 => 28,
),
)