PHP-使用foreach显示2维数组

时间:2019-06-27 13:21:11

标签: php arrays

我想显示一个二维数组。我尝试使用double foreach做到这一点,但我有点失落。它返回是我一个空的TD,我不知道为什么。我正在使用ZendFramework。我应该使用其他解决方案并离开foreach解决方案,还是只是错过了什么?

数组(一个数组中有7个数组,列始终相同):

array(7) {
[0]=>
array(11) {
["'01.drplapostej-1'"]=>
string(20) "01. DRP La poste J-1"
["import"]=>
string(1) "0"
["radm_ok"]=>
string(1) "0"
["radm_rejet"]=>
string(1) "0"
["radm_ko"]=>
string(1) "0"
["rpec_ok"]=>
string(1) "0"
["rpec_rejet"]=>
string(1) "0"
["rpec_ko"]=>
string(1) "0"
["factu_ok"]=>
string(1) "0"
["factu_rejet"]=>
string(1) "0"
["factu_ko"]=>
string(1) "0"
}
[1]=>
array(11) {
["'01.drplapostej-1'"]=>
string(20) "02. DRL La poste J-1"
["import"]=>
string(2) "80"
["radm_ok"]=>
string(1) "0"
["radm_rejet"]=>
string(1) "0"
["radm_ko"]=>
string(1) "0"
["rpec_ok"]=>
string(1) "0"
["rpec_rejet"]=>
string(1) "0"
["rpec_ko"]=>
string(1) "0"
["factu_ok"]=>
string(1) "0"
["factu_rejet"]=>
string(1) "0"
["factu_ko"]=>
string(1) "0"
}

我想做的事情:

<table>
<tr>
<th>01.DRPLAPOSTEJ-1</th>
<th>IMPORT</th> 
<th>RADM_OK</th>
<th>RADM_REJET</th>
<th>RADM_KO</th>
<th>RPEC_OK</th>
<th>RPEC_REJET</th>
<th>RPEC_KO</th>
<th>FACTU_OK</th>
<th>FACTU_REJET</th>
<th>FACTU_KO</th>
</tr>
<?php foreach ($this->suiviprodjours as $value): ?>
  <?php foreach ($value as $key => $val): ?>
<tr>
<td <?php echo $val[$key]["01.DRPLAPOSTEJ-1"].'<br>';  ?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</table>

结果:

enter image description here

2 个答案:

答案 0 :(得分:2)

您需要像下面这样应用foreach():-

<?php foreach($array as $arr){?>
    <tr>
        <?php foreach($arr as $value){?>
            <td><?php echo $value;?></td>
        <?php } ?>
    </tr>
<?php } ?>

因此完整的代码将是:

<table>
    <tr>
        <th>01.DRPLAPOSTEJ-1</th>
        <th>IMPORT</th> 
        <th>RADM_OK</th>
        <th>RADM_REJET</th>
        <th>RADM_KO</th>
        <th>RPEC_OK</th>
        <th>RPEC_REJET</th>
        <th>RPEC_KO</th>
        <th>FACTU_OK</th>
        <th>FACTU_REJET</th>
        <th>FACTU_KO</th>
    </tr>
    <?php foreach($array as $arr){?>
        <tr>
            <?php foreach($arr as $value){?>
                <td><?php echo $value;?></td>
            <?php } ?>
        </tr>
    <?php } ?>
</table>

答案 1 :(得分:2)

您可以将此代码段用于动态标头和数据,

echo "<table>";
$keys = array_keys($arr[0]);
//if you want to make upper cases
$keys = array_map("strtoupper", $keys);
echo "<tr><th>";
echo implode("</th><th>", $keys);
echo "</th></tr>";
foreach ($arr as $key => $value) {
    echo "<tr><td>";
    echo implode("</td><td>", $value);
    echo "</td></tr>";
}
echo "</table>";

Demo