php - 来自多维数组的php动态表
问题描述
你能告诉我如何为“动态”html表实现这个想法吗?我有一个数组
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
现在从键“标签”即时创建表格列
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
问题是如何将“fname”键放在第一列,“lname”放在第二列,“description”放在第三列。
通过这部分代码,我试图将数据放在所有列中
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
另外我的想法不是硬编码数组键以供多次使用(标签和数据除外)。
解决方案
首先,我将重新映射数据以循环处理它。
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
现在打印出带有标题的标签。
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
遍历行并创建 HTML。
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
这给出了如下表
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
推荐阅读
- code-complexity - nx 系列的代码复杂度是多少?
- javascript - 执行条件语句(v-if 和 v-else)
- outlook - 日历会议中的 Outlook 加载项
- python - 不同数据点的权重不同?(从零开始的逻辑回归)
- python - 我的井字游戏 Python 脚本有问题
- laravel - 使用查询生成器根据条件计数不工作
- ios - IOS 14中的UIDatePicker在键盘中显示背景tabBar
- python - Robot Framework 如何获取文本项
- c# - 从 var 中获取值
- java - 旋转 x 轴标签时,MPAndroidChart 图表在数据集更改时垂直调整大小