如何将数组转换为html表

时间:2010-12-25 10:02:19

标签: php

有人可以帮助我使用这个阵列吗?我想创建一个最多5列,最多15行的表。例如,如果只有4行,那么只显示4行而不是15行。如果只有3个单元格有数据,那么剩下的2个应该用$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>';

3 个答案:

答案 0 :(得分:11)

让我们调用您的数组$rows,好吗?

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

使用foreach更适合在php中循环使用数组,并且它可以极大地提高代码的可读性。另外,您需要的唯一变量是包含数组本身的变量。

答案 1 :(得分:2)

退房:

PHP array to table

Or this class

这基本上是简单的逻辑:

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>"; 

答案 2 :(得分:2)

这是我编写的一个代码片段,用于测试将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;
}