首页 > 解决方案 > 从数组中填充 PHP 表

问题描述

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

标签: phploopshtml-table

解决方案


据我所知,这就是你如何填充一个简单的 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>';

推荐阅读