codeigniter中的动态行列

时间:2016-10-27 06:22:51

标签: codeigniter

我只需要使用foreach获取数组并创建一个表格为:

<?php foreach ($trainee as $key => $value): ?>
 <tr>
  <td><?= $value->TraineeID ?></td>
 </tr> 
<?php endforeach?>

但是当表列数未固定时,我无法创建列及其值。

数据阵列:

Array(
    [0] => stdClass Object
        (
            [TraineeID] => 30012
            [Inv.1] => 720
            [Inv.2] => 2100
            [Inv.3] => 3540
            [Inv.4] => 4920
            [Inv.5] => 6300
            [Inv.6] => 7800
            [Inv.7] => 8700
        )
    [1] => stdClass Object
        (
            [TraineeID] => 30033
            [Inv.1] => 720
            [Inv.2] => 2100
            [Inv.3] => 3540
            [Inv.4] => 4920
            [Inv.5] => 6300
            [Inv.6] => 7800
            [Inv.7] => 8700
        )
    [2] => stdClass Object
        (
            [TraineeID] => 30037
            [Inv.1] => 720
            [Inv.2] => 2100
            [Inv.3] => 3540
            [Inv.4] => 4920
            [Inv.5] => 6300
            [Inv.6] => 7800
            [Inv.7] => 8700
        )
    [3] => stdClass Object
        (
            [TraineeID] => 30038
            [Inv.1] => 720
            [Inv.2] => 2100
            [Inv.3] => 3540
            [Inv.4] => 4920
            [Inv.5] => 6300
            [Inv.6] => 7800
            [Inv.7] => 8700
        )
)

所需的输出如下:

TraineeID   Inv.1   Inv.2   Inv.3   Inv.4   Inv.5   Inv.6   Inv.7
30012        720    2100    3540    4920    6300    7800    8700
30033        720    2100    3540    4920    6300    7800    8700
30037        720    2100    3540    4920    6300    7800    8700
30038        720    2100    3540    4920    6300    7800    8700

2 个答案:

答案 0 :(得分:2)

试试这个

<?php 
    foreach ($trainee as $traine):
        echo "<tr>";
        $tds = get_object_vars($traine);
        foreach ($tds as $property => $value) {
            echo sprintf("<td>%s</td>",$traine->{$property});
        }
        echo "</tr> ";
    endforeach;
?>

答案 1 :(得分:0)

非常简单。使用此

<?php foreach ($trainee as $key => $value): ?>
<tr>
 <td><?= $value->TraineeID ?></td>
 <td><?= $value->Inv.1 ?></td>
 <td><?= $value->Inv.2 ?></td>
 <td><?= $value->Inv.3 ?></td>
 <td><?= $value->Inv.4 ?></td>
 <td><?= $value->Inv.5 ?></td>
 <td><?= $value->Inv.6 ?></td>
 <td><?= $value->Inv.7 ?></td>
</tr> 
<?php endforeach?>