繁体   English   中英

如何将数组转换为html表

[英]How to convert an array to a html table

有人可以帮我解决这个问题吗? 我想创建一个表,该表最多5列,最多15行。 例如,如果只有4行,那么应该只显示4行而不是15行。如果只有3个具有数据的单元格,则剩余的2个单元应该用$nbsp;填充$nbsp;

这是我的示例数组:

Array
(
    [0] => Array
        (
            [name] => test1
            [item_id] => 1
        )
    [1] => Array
        (
            [name] => test2
            [item_id] => 2
        )
    [2] => Array
        (
            [name] => test3
            [item_id] => 3
        )
    [3] => Array
        (
            [name] => test4
            [item_id] => 4
        )
    [4] => Array
        (
            [name] => test5
            [item_id] => 5
        )
    [5] => Array
        (
            [name] => test6
            [item_id] => 6
        )
)

如果添加了新行,我的数据将重复。 这是我目前的问题。

$row = count( $array ) / 5;
$col = 5;

echo'<table border="1" width="700">';

for( $i = 0; $i < $row; $i++ )
{
    echo'<tr>';
    for( $j = 0; $j < $col; $j++ ) {
        if( ! empty( $array[$j] ) ) {
            echo '<td>'.$array[$j]['item_id'].'</td>';
        }
    }
    echo'</tr>';
}

echo'</table>';

我们将数组称为$rows ,好吗?

echo "<table>";
foreach ($rows as $row) {
   echo "<tr>";
   foreach ($row as $column) {
      echo "<td>$column</td>";
   }
   echo "</tr>";
}    
echo "</table>";

使用foreach在php中循环槽数组更惯用,它大大提高了代码的可读性。 另外,您所需的唯一变量是包含数组本身的变量。

这是我编写的用于测试将php数组转换为html的代码段。

    $row = array(
        'column 1' => 'value',
        'column 2' => 'value',
        'column 3' => 'value',
        'column 4' => 'value',
        'column 5' => 'value',
        'column 6' => 'value',
        'column 7' => 'value',
    );

    $rows = array($row, $row, $row, $row, $row, $row, $row, $row, $row, $row);

    print array_to_html($rows);


function array_to_html($data) {
    $report = "";

    if (count($data) > 0) {

        $report .= "<table>";
        $report .= sprintf("<tr><th>%s</th></tr>", join("</th><th>", array_keys($data[0])));

        foreach ($data as $row) {

            $report .= "<tr>";

            foreach ($row as $column) {
                $report .= "<td>$column</td>";
            }
            $report .= "</tr>";
        }
        $report .= "</table>";
    } else {
        $report = "No data";
    }

    return $report;
}

查看:

PHP数组到表

还是这个班

基本上是简单的逻辑,如下所示:

echo "<table border=\"5\" cellpadding=\"10\">";

for ($i=0; $i < count($input); $i++)
{
    echo "<tr>";
    for ($c=0; $c<$cols; $c++)
    {
      echo "<td>$input[$i]</td>";
    }
    echo "</tr>";
}

echo "</table>"; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM