【问题标题】:3 Dimensional Associative Array to HTML table3 维关联数组到 HTML 表
【发布时间】:2017-07-04 06:42:08
【问题描述】:

这就是我的数组的样子。

(int) Year 1 => array(
'Department 1' => array(
    'Sales' => '12345'

),
'Department 2' => array(
    'Sales' => '12345'

),
),
(int) Year 2 => array(
'Department 1' => array(
    'Sales' => '12345'

),
'Department 2' => array(
    'Sales' => '12345'

),

)

我希望能够创建一个表,其中标题是 X 轴上的年份。 Y 轴需要以部门名称开头。相邻单元格需要在一个单元格中包含销售额、收入和总额。

它应该看起来像这样......

      Department____|   ___YEAR1_______      | __Year2

      Department 1  |Sales  [dept 1][year 1] |    Sales[dept 1][year 2]
      Department 2  |Sales  [dept 2][year 1] |  Sales  [dept 2][year 2] 

我使用了嵌套的 foreach 循环

foreach($List as $key=>$row) {
echo "<tr><td>".$key."</td>";



foreach($row as $key2=>$col){

    echo "<td>" . 'Sales: '.round($col['sales'],2) ."</td>";

}
echo "</tr>";

}
echo "</table>"; ?>

但它在 x 轴上打印了部门名称在 y 轴上显示年份的表格。如何在 x 轴上获得年份,在 y 轴上获得部门。

【问题讨论】:

  • 是否保证数组的所有行都有相同的部门?
  • 是的。这基本上是按年划分的部门。该数组每年使用相同的部门列表构建。

标签: php html multidimensional-array html-table


【解决方案1】:

问题是您的数组的维度与您想要为您的表格遍历它们的顺序不对应。您需要显式提取键以在嵌套循环中遍历它们。

$years = array_keys($List);
// Print column headings
echo "<table><thead><tr><th>Department</th>";
foreach ($years as $year) {
    echo "<th>$year</th>";
}
echo "</tr></thead>";
// Print data rows
echo "<tbody>"
foreach (array_keys($List[$years[0]]) as $dept) {
    echo "<tr><th>$dept</th>";
    foreach ($years as $year) {
        echo "<td>{$List[$year][$dept]['Sales'}]</td>";
    }
    echo "</tr>";
}
echo "</tbody></table>";

正如我所提到的,这取决于所有年份都有相同的部门。如果随着时间的推移添加新部门,它将无法正常工作。您可以使用array_reduce 合并所有部门列表来解决此问题,我将把它留给读者作为练习。

【讨论】:

  • 非常感谢。我从来没有想过用 dept 作为键来推送数组键。
猜你喜欢
  • 2014-05-17
  • 2016-11-08
  • 2013-10-26
  • 2017-09-17
  • 1970-01-01
  • 2014-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
相关资源
最近更新 更多