【问题标题】:Filling up <td> in PHP table from array从数组中填充 PHP 表中的 <td>
【发布时间】:2018-07-20 16:03:21
【问题描述】:

我在尝试将数据正确显示到 &lt;td&gt; 列时遇到了困难。我的表头和第一个表列工作正常。我似乎无法理解如何正确显示其他数据。

【问题讨论】:

    标签: php loops html-table


    【解决方案1】:

    你有很多语法错误。 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>';
    ?>
    

    【讨论】:

      【解决方案2】:

      据我所知,这就是填充简单 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>';
      

      【讨论】:

      • @skoteinos 我看到您的月份列&lt;td&gt; 没有包含在&lt;tr&gt; 中,请检查表层次结构。一个&lt;tr&gt;必须包含多个&lt;td&gt;s,并且不能单独存在&lt;td&gt;
      • 如果您希望每行的第一列是月份名称,请检查我编辑的答案
      猜你喜欢
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多