PHP数组键值重复错误

时间:2016-06-30 10:24:58

标签: php

I have following array :
Array
(
[0] => stdClass Object
(
    [sbu_name] => DISTRIBUTION CONSULTING
    [2016-06-26 TO 2016-07-2] => 
    [2016-06-5 TO 2016-06-11] => 
    [2016-06-19 TO 2016-06-25] => 57
)

[1] => stdClass Object
    (
        [sbu_name] => PMC
        [2016-06-26 TO 2016-07-2] => 467.25
        [2016-06-5 TO 2016-06-11] => 10
        [2016-06-19 TO 2016-06-25] => 
    )

[2] => stdClass Object
    (
        [sbu_name] => VAI
        [2016-06-26 TO 2016-07-2] => 
        [2016-06-5 TO 2016-06-11] => 
        [2016-06-19 TO 2016-06-25] => 
    )
)

我必须打印这个数组的密钥,我已经使用下面的代码实现了这个

foreach ($collection as $key => $val) {
    foreach ($val as $key2 => $newVal) { ?>
        <th><?php echo $key2; ?></th>
    <?php
    }
}

但输出显示如此重复。 我不希望这样: enter image description here

2 个答案:

答案 0 :(得分:0)

您将全部打印为表标题th标记。这将导致您在图像中显示的输出。所有按键只能在一行上。

对于每个数组元素,您应该为tr多个td

foreach ($collection as $key => $val) {
    echo "<tr>";
    foreach ((array)$val as $key2 => $newVal) {
        echo sprintf("<td>%s</td>", $key2);
    }
    echo "</tr>";
}

答案 1 :(得分:0)

您多次打印标题(每个结果一次),您应该只执行一次:

<table><thead><tr>
<?php
if (is_array($collection) && count($collection) > 0) {
    $val = current($collection);
    foreach ((array)$val as $key2 => $newVal) { ?>
        <th><?php echo $key2; ?></th>
    <?php
    }
}?>
</tr></thead>
<tbody>
<?php
foreach ($collection as $key => $val) { ?>
    <tr>
    <?php 
    foreach ($val as $key2 => $newVal) { ?>
        <td><?php echo $newVal; ?></th>
    <?php } ?>
    </tr> 
   <?php
} ?>
</tbody>
</table>