如何从数组创建表?

时间:2011-11-17 02:05:53

标签: php arrays foreach html-table

从这个数组中按特定顺序创建一些表格有点困难:$test

数组如下所示:

Array
(
    [ET5] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 430
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 406
            )
        )
    )
    [FA] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 0
            )
        )                   
        [1] => Array(
            [0] => Array(
                [total] => 0
            )
        )
    )
    [ET5] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 189
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 228
            )
        )
    )
    [FA] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 0
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 0
            )
        )
    )
)

我要创建的表应该如下所示:

表1

test1      test2   test3
ET5        430     189
FA         0       0

表2

test1      test2    test3
ET5        406      228
FA         0        0

test1, test2, test3是已知字符串

我有点卡在这一点上,注意ET5中的值是如何在两个表中的。

关于这个的任何想法?

1 个答案:

答案 0 :(得分:1)

你绝对不应该像上面那样覆盖数组的键。

我会在每个表格中将您想要的内容添加为已经多维数组的数组...

$test = array(
    [0] => array(
        [ET5] => array(), //rest of inner contents inside these arrays of course
        [FA] => array()
    ),
    [1] => array(
        [ET5] => array(),
        [FA] => array()
    )
);

然后像在任何数组上一样运行foreach循环:

<?php foreach($test AS $key => $val): ?>
<table>
    <tr>
        <th>Test1</th>
        <th>Test2</th>
        <th>Test3</th>
    </tr>
    <?php foreach($val AS $v => $info): ?>
    <tr>
        <td><?php echo $v; ?></td>
        <td><?php echo $info[0][0]['total']; ?></td>
        <td><?php echo $info[1][0]['total']; ?></td>
    </tr>
    <?php endforeach; ?>
</table>    
<?php endforeach; ?>