,适合处理结构规整的索引二维数组,代码更紧凑。
1、确保数组为纯索引格式,如:$data = [['张三', 25], ['李四', 30]];
2、提取表头数组:$headers = ['姓名', '年龄'];
3、生成表头行:$headerRow = 'zuojiankuohaophpcntr><th>' . implode('</th><th>', $headers) . '</th></tr>';;
4、定义单元格转义函数:$escape = function($v) { return htmlspecialchars($v); };
5、对每行执行映射:$rows = array_map(function($row) use ($escape) { return '<tr><td>' . implode('</td><td>', array_map($escape, $row)) . '</td></tr>'; }, $data);;
6、合并所有行:$tableBody = implode('', $rows);
7、组合完整表格:$html = '<table border="1">' . $headerRow . $tableBody . '</table>';。
三、使用PHP内置函数array_column提取列并构造表格
该方法适用于需按特定键动态提取列数据的场景,尤其适合从关联数组中分离出某几列进行展示,灵活性高。
ChatDOC
ChatDOC是一款基于chatgpt的文件阅读助手,可以快速从pdf中提取、定位和总结信息
下载
1、准备关联数组:$users = [['id'=>1,'name'=>'王五','score'=>88],['id'=>2,'name'=>'赵六','score'=>92]];
2、指定要显示的列名:$columns = ['name', 'score'];
3、生成表头:echo '<th>' . implode('</th><th>', array_map('htmlspecialchars', $columns)) . '</th>';;
4、遍历原始数组,对每行提取指定列:$rowValues = array_map(function($col) use ($user) { return $user[$col]; }, $columns);;
5、将提取值转义后拼入
:echo '<td>' . implode('</td><td>', array_map('htmlspecialchars', $rowValues)) . '</td>';;
6、包裹每行于
|