PHP如何将嵌套JSON数组循环渲染为表格或列表而非单行展示
原代码核心错误
- 遍历设备列表时调用的是所有车辆中第一辆车的配置数据,不是当前遍历车辆的对应配置,导致所有车辆的配置展示完全相同
- 每一项配置都单独生成
<td>标签,导致表格列数完全错位,应该把所有配置项放在同一<td>内用无序列表展示 <tr>行闭合标签写在了车辆遍历循环外面,导致所有车辆数据都被塞进同一行渲染- 渲染图片时固定取数组第一个元素的地址,没有随循环索引切换,所有展示的图片都是车辆的第一张图
修正后可直接运行的代码
<?php $url = 'https://gw.bilinfo.net/listingapi/api/export'; // 用户名和密码认证 $auth = base64_encode("demo:ocfB6XzF73"); // 生成带基础认证的HTTP上下文 $context = stream_context_create([ 'http' => ['header' => "Authorization: Basic $auth"] ]); // 请求接口数据 $data = file_get_contents($url, false, $context); $escaped = json_decode($data); // 初始化表格变量,加了基础样式方便查看 $temp = "<table border='1' cellpadding='8' cellspacing='0'>"; // 表头定义 $temp .= "<tr>"; $temp .= "<th>Bil</th>"; $temp .= "<th>Model</th>"; $temp .= "<th>Motor</th>"; $temp .= "<th>Drivmiddel</th>"; $temp .= "<th>Udstyr</th>"; $temp .= "<th>Billeder</th>"; $temp .= "</tr>"; // 动态生成表格行 foreach ($escaped->Vehicles as $vehicle) { $temp .= "<tr>"; $temp .= "<td>" . $vehicle->Make . "</td>"; $temp .= "<td>" . $vehicle->Model . "</td>"; $temp .= "<td>" . $vehicle->Motor . "</td>"; $temp .= "<td>" . $vehicle->Propellant . "</td>"; // 所有配置项放在同一个td内,用列表渲染 $temp .= "<td><ul>"; foreach($vehicle->EquipmentList as $EquipmentItem){ $temp .= "<li>" . $EquipmentItem . "</li>"; } $temp .= "</ul></td>"; // 所有图片放在同一个td内,加了宽度限制避免页面变形 $temp .= "<td>"; for ($p = 0; $p < $vehicle->PictureCount; $p++) { $temp .= "<img width='100' src='" . $vehicle->Pictures[$p] . "' style='margin:4px;'>"; } $temp .= "</td>"; // 每行遍历完成后立即闭合行标签 $temp .= "</tr>"; } // 闭合表格标签 $temp .= "</table>"; // 输出渲染完成的表格 echo $temp; ?>
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

