如何将数组转换为html表 [英] How to convert an array to a html table

查看:255
本文介绍了如何将数组转换为html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can someone help me with this array that I have? I want to create a table that is a maximum of 5 columns and a maximum of 15 rows. If there are only 4 rows, for example, then only 4 rows should be shown instead of the 15. If there are only 3 cells that have data then the the remaining 2 should be padded with $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
        )
)


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


My data repeats if there is a new row added. This is my issue at present.

$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,好吗?

Let's call your array $rows, ok?

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

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

Using foreach is more idiomatic for looping trough arrays in php, and it greatly increase your code's readability. Plus, the only variable you need for this is one containing the array itself.

这篇关于如何将数组转换为html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆