【发布时间】:2018-07-20 16:03:21
【问题描述】:
我在尝试将数据正确显示到 <td> 列时遇到了困难。我的表头和第一个表列工作正常。我似乎无法理解如何正确显示其他数据。
【问题讨论】:
标签: php loops html-table
我在尝试将数据正确显示到 <td> 列时遇到了困难。我的表头和第一个表列工作正常。我似乎无法理解如何正确显示其他数据。
【问题讨论】:
标签: php loops html-table
你有很多语法错误。 Echo 不需要括号。每个单元格都需要一个 td 标签。
此外,您使用的数组具有何种格式也是不明确的。根据这一点,解决方案可能会出现。
不过,这里有一个建议。您可能需要根据阵列的组织对其进行修改。
<?php
//get json data
$data = json_decode($output, true);
//start table
echo '<table><tr><th> Month </th>';
//table headers
for ($i = 0; $i < 4; $i++)
{
echo '<th>' . $data['series'][$i]['name'] . '</th>';
}
echo '</tr>';
//column of months
$number = 0;
foreach ($data['categories'] as $value)
{
foreach($data['series'] as $inst)
{
$month_data = $month_data . "<td>" . $inst['data'][$number] . "</td>";
};
echo "<tr><td>$value</td>" . $month_data . "</tr>";
$number++;
unset($month_data);
};
echo '</table>';
?>
我称为 $month_data 的部分将根据数组的组织方式而改变。要查看它是如何组织的,请使用:
<?php
echo '<pre>';
print_r($data);
echo '</pre>';
?>
【讨论】:
据我所知,这就是填充简单 2x2 数组的方式
foreach($rows as $row){
echo '<tr>';
// create first td (column name)
echo '<td>';
echo $month[$row];
echo '</td>';
// create the rest td (data value)
foreach($columns as $column){
echo '<td>';
echo $data[$row][$column];
echo '</td'>;
}
echo '</tr>';
}
您的行将是城市名称和月份名称作为列
所以我的解决方案
//start table
echo '<table>';
//first row
echo '<tr>';
//first header
echo '<th> Month </th>';
//rest of headers
for ($i = 0; $i < 4; $i++) {
echo '<th>' .$data['series'][$i]['name']. '</th>';
}
echo '</tr>';
//rest of rows
for ($x = 0; $x < 12; $x++){
echo '<tr>';
//first column
echo '</td>';
echo $data['categories'][$x];
echo '</td>';
//rest of columns
for ($i = 0; $i < 4; $i++) {
echo '<td>';
echo $data['series'][$i]['data'][$x];
echo('</td>');
}
echo '</tr>';
}
echo '</table>';
【讨论】:
<td> 没有包含在<tr> 中,请检查表层次结构。一个<tr>必须包含多个<td>s,并且不能单独存在<td>