如何利用PHP数组生成指定4列HTML表格?代码修改咨询
解决PHP数组生成4列HTML表格的问题
咱们先梳理下现有代码的问题所在:
- HTML的表头是3列(location、product、qty),和你要的4列布局完全不匹配
- JS里用
eval解析JSON不安全,而且遍历方式错了——你返回的是键值对对象(比如{"A1": [...], "A2": [...]),不是数组,所以obj.length根本拿不到正确长度,之前的循环逻辑也只是生成3列的行,完全不符合需求 - PHP里还有个小坑:
$data[loc_a]没加引号,会被PHP当成常量解析,容易出问题
接下来咱们逐个修改:
1. 调整HTML表格结构
把表头改成你需要的4列,去掉不需要的product和qty列:
<table class="table table-bordered"> <thead> <tr> <th class="header_center" width=100>location 1</th> <th class="header_center" width=100>location 2</th> <th class="header_center" width=100>location 3</th> <th class="header_center" width=100>location 4</th> </tr> </thead> <tbody id="table_contents"> </tbody> </table>
2. 重写JS渲染逻辑
核心思路是:按行来生成,每一行对应A1、A2、A3、A4这四个分组里的同位置元素。同时替换不安全的eval为JSON.parse:
$.post("function.htm", { template : "IU00", action : "get_location_list", }, function( response ){ $("#table_contents").empty(); // 安全解析JSON,替代eval const locationGroups = JSON.parse(response); // 按顺序提取四个分组的数组,避免键顺序混乱;如果某个分组不存在就用空数组兜底 const groups = [ locationGroups.A1 || [], locationGroups.A2 || [], locationGroups.A3 || [], locationGroups.A4 || [] ]; // 找到最长的分组长度,确定要渲染多少行 const maxRowCount = Math.max(...groups.map(group => group.length)); // 循环每一行,生成4列的单元格 for(let rowIndex = 0; rowIndex < maxRowCount; rowIndex++){ let rowHtml = "<tr>"; groups.forEach(group => { // 如果当前行有元素就显示,没有则留空 const loc = group[rowIndex] || ""; rowHtml += `<td>${loc}</td>`; }); rowHtml += "</tr>"; $("#table_contents").append(rowHtml); } });
3. PHP代码的小修复(避免潜在bug)
主要是修正数组索引的引号问题,同时建议替换已废弃的mysql扩展为mysqli:
function get_location_list() { global $connect; $query = "select location , SUBSTRING_INDEX(SUBSTRING_INDEX(location,'-',1),'-',-1) loc_a , SUBSTRING_INDEX(SUBSTRING_INDEX(location,'-',2),'-',-1) loc_b , SUBSTRING_INDEX(SUBSTRING_INDEX(location,'-',3),'-',-1) loc_c from stock_location where location> '' order by loc_a, loc_b * 1, loc_c * 1 limit 100"; // 替换mysql_query为mysqli_query,mysql扩展已被PHP废弃 $result = mysqli_query($connect, $query); $arr_result = array(); while( $data = mysqli_fetch_array( $result ) ) { // $data['loc_a']必须加引号,否则会被当成常量解析 $arr_result[$data['loc_a']][] = $data['location']; } echo json_encode( $arr_result ); }
这样修改后,就能生成你想要的4列布局表格了——每一行对应四个分组的同位置元素,长度不足的分组会自动留空单元格。
内容的提问来源于stack exchange,提问作者장경준
相关产品推荐
相关产品推荐

