首页 > 解决方案 > 来自多维数组的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;
}

另外我的想法不是硬编码数组键以供多次使用(标签和数据除外)。

标签: phparraysdynamic

解决方案


首先,我将重新映射数据以循环处理它。

$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>

推荐阅读