PHP Foreach数组转表格显示

标签 php arrays foreach

我有一个数组 $day 并且想以表格形式显示这个数组(我正在使用 CI)

Array ( 
[START_EXECUTION] => 
    Array ( 
        [0] => 27-OCT-14 
        [1] => 28-OCT-14 
        [2] => 29-OCT-14 
          ) 
[NUM_OF_POPULATION] => 
    Array ( 
        [0] => 6171 
        [1] => 6990 
        [2] => 6882 
          ) 
[SUM_AMOUNT] => 
        Array ( 
        [0] => 361154716.01 
        [1] => 409210099.77 
        [2] => 407191552.71 
          ) 
)

这是我在 View 中使用的代码:

<?php
if(count($day)>0){
    print_r($day);
    foreach($day as $index => $dt1_element){    
?>        
    <table class='table'>
        <tr>
        <td><?= $index ?></td>
        </tr>        
<?php
    foreach($dt1_element as $row){        
?>
        </tr>
        <td><?= $row ?></td>
<?php
    }
?>
        </tr>
<?php
    }
?>
    </table>
<?php
    }
?

但是我得到的是这样的:

START_EXECUTION
27-OCT-14
28-OCT-14
29-OCT-14

NUM_OF_POPULATION
6171
6990
6882

SUM_AMOUNT
361154716.01
409210099.77
407191552.71

结果应该是:

START_EXECUTION   NUM_OF_POPULATION   SUM_AMOUNT
27-OCT-14         6171                361154716.01
28-OCT-14         6990                409210099.77
29-OCT-14         6882                407191552.71

请告诉我正确的 foreach 以获得所需的结果。谢谢

最佳答案

试试这个:

echo '<table>';

$cols = array_keys($day);
echo '<tr>';
foreach ($cols as $col) echo '<th>' . $col . '</th>';
echo '</tr>';

foreach ($day[$cols[0]] as $i => $null) {
    echo '<tr>';
    foreach ($cols as $col) echo '<td>' . $day[$col][$i] . '</td>';
    echo '</tr>';
}

echo '</table>';

enter image description here

demo

关于PHP Foreach数组转表格显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27125276/

相关文章:

javascript - 用于在 Google Maps v3 上创建多条路线的数组

javascript - else 语句不起作用

php - 加入多对一

javascript - 为什么 if 语句会阻塞在 while 循环中?

c - 使指针指向数组的末尾

arrays - SystemVerilog foreach 语法,用于循环遍历多维数组的低维

c# - foreach 特定列中的标签,C#

去除标签的 PHP 函数,白名单标签和属性列表除外

php - 交友网站算法

php - 使用 php 和 curl 抓取客户端证书请求