php - 如何从多维数组中制作一个好的 html 表示表?
问题描述
我需要使用维度数组将我的数据库结果转换为一个漂亮的 HTML 表。我知道这是一个非常有条件的情况。
我正在使用 CodeIgniter 并且已经有一些数据。我试图提取数据库结果并制作新的数组格式。现在我对如何将其很好地格式化为 HTML 表格感到困惑。
$schedule = [];
foreach($this->data['jadwal_kelas'] AS $row)
{
$schedule['class_name'][$row->class_name]['time'][$row->start.'-'.$row->end] = ['room' => $row->room, 'mentor_code' => $row->mentor_code];
}
这里的结果使用print_r
<pre>Array
(
[class_name] => Array
(
[E-1] => Array
(
[time] => Array
(
[07:30:00-08:30:00] => Array
(
[room] => A
[mentor_code] => TPA-1
)
[08:30:00-09:30:00] => Array
(
[room] => A
[mentor_code] => TPA-1
)
[10:00:00-11:00:00] => Array
(
[room] => A
[mentor_code] => FIS-1
)
[11:00:00-12:00:00] => Array
(
[room] => A
[mentor_code] => FIS-1
)
)
)
[E-2] => Array
(
[time] => Array
(
[07:30:00-08:30:00] => Array
(
[room] => D
[mentor_code] => FIS-1
)
[08:30:00-09:30:00] => Array
(
[room] => D
[mentor_code] => FIS-1
)
[10:00:00-11:00:00] => Array
(
[room] => D
[mentor_code] => BIO-1
)
[11:00:00-12:00:00] => Array
(
[room] => D
[mentor_code] => BIO-1
)
)
)
)
)
...
</pre>
我希望 HTML 表如下所示:
Time | E1 | E2 | E3 |
-------------|-------|--------|--------|
07:30-08:30 | TPA-1 | FIS-1 | |
08:30-09:30 | TPA-1 | FIS-1 | |
10:00-11:00 | FIS-1 | BIO-1 | MATH-1 |
11:00-12:00 | FIS-1 | BIO-1 | MATH-1 |
...
我不知道如何loop
通过数组来创建一个像上面这样的表。如果这里有人能指出我正确的方向,将不胜感激。谢谢你。
解决方案
这对我有用:
<?php
$available_sections = array();
$available_times = array();
foreach ($a['class_name'] as $s => $records)
{
$available_sections[$s] = 1;
foreach ($records['time'] as $t => $values)
$available_times[$t] = 1;
}
ksort($available_times);
$output = '
<table border="1" cellpadding="4" style="font-family: Arial; font-size: 12px;">
<tr>
<th>Time</th>';
foreach ($available_sections as $as => $v)
$output .= '<th>'.$as.'</th>';
$output .= '
</tr>';
foreach ($available_times as $at => $v)
{
$output .= '
<tr>
<td>'.$at.'</td>';
foreach ($available_sections as $as => $v2)
$output .= '<td>'.(isset($a['class_name'][$as]['time'][$at]) ? $a['class_name'][$as]['time'][$at]['mentor_code'] : '').'</td>';
$output .= '</tr>';
}
$output .= '
</table>';
echo $output;
结果
我希望这有帮助!
推荐阅读
- mysql - MySQL JSON - 如何在匹配路径的所有元素上使用 JSON_SET?
- sql-server - 在 SQL Server 中插入文件/文件名以在处理后提取
- mediawiki - 如何比较两个 MediaWiki 站点
- javascript - 将一维数组转换为多维数组
- aws-api-gateway - 如何在 AWS API Gateway 中映射 / 到 index.html
- ios - 在 iOS 上无需身份验证即可跟踪付费内容
- javascript - 如何在这个带有虚拟页面项的 AngularJS 应用程序中平滑地将页面滚动到顶部?
- amazon-web-services - 如何在 Eclipse 和 Window 10 上配置 AWS SAM
- python - 如何保留更改的python工作目录
- python-3.x - 将无理数放入分数时,sympy 返回 TypeError