从多维数组创建表

时间:2019-07-19 09:13:53

标签: php arrays

我有多维数组,需要用它们在html中创建表格。我有一个目录编号与表格中的日期匹配的问题。

我创建了一个数组(下面很少部分):

数组包含日期=> CatalogNo => [catalogNo],[count],[date]

Array
(
[2019/07/19] => Array
    (

        [71156] => Array
            (
                [catalogNo] => 71156
                [count] => 22
                [date] => 2019/07/19
            )

        [71157] => Array
            (
                [catalogNo] => 71157
                [count] => 21
                [date] => 2019/07/19
            )

        [71221] => Array
            (
                [catalogNo] => 71221
                [count] => 217
                [date] => 2019/07/19
            )
)

[2019/07/18] => Array
    (
        [71156] => Array
            (
                [catalogNo] => 71156
                [count] => 26
                [date] => 2019/07/18
            )

        [71157] => Array
            (
                [catalogNo] => 71157
                [count] => 25
                [date] => 2019/07/19
            )

        [71221] => Array
            (
                [catalogNo] => 71221
                [count] => 281
                [date] => 2019/07/19
            )

        [71222] => Array
            (
                [catalogNo] => 71221
                [count] => 173
                [date] => 2019/07/19
            )
 ...

我做了这样的事情,但这很糟糕。我不知道该怎么做。

$dane_arr <-这是整个数组

<table>
<tr>
    <th>CatalogNo</th>
    <?php
    foreach( $dane_arr as $k => $v )
    {
        ?>
        <th><?php echo $k ?></th>
        <?php
    }
    ?>
</tr>
<?php
foreach( $dane_arr as $k_date => $date_ )
{
    foreach( $date_ as $k_nrArt_ => $nrArt_ )
    { ?>
        <tr>
            <td><?php echo $nrArt_['catalogNo'] ?></td>
            <td><?php echo $nrArt_['count'] ?></td>
        </tr>
        <?php
    }
}
?>

`

CatalogNo中有重复项,当然日期也不适合。

我想创建表,诸如此类:

CatalogNo | 2019/07/18 | 2019/07/19 | ... 71156 26 22 ... 71157 25 21 ... 71221 281 217 ... 71222 173 0 ... (当然,“ CatalogNo”中没有重复项)

1 个答案:

答案 0 :(得分:0)

您首先需要重新排列阵列。然后获取所有日期,并创建表格:

<?php

$catalogUsage = [];
foreach ($dane_arr as $date => $catalogs) {
    foreach( $catalogs as $catalogNo => $catalog) {
         $catalogUsage[$catalogNo][$date] = $catalog['count'];
    }
}

$allDates = array_keys($dane_arr);

?>
<table>
<tr>
    <th>CatalogNo</th>
    <?php

    foreach ($allDates as $date) {
        echo "<th>$date</th>"
    }

    ?>
</tr>
<?php

foreach($catalogUsage as $catalogNo => $counts)
{
    echo "<tr><td>$catalogNo</td>";
    foreach ($allDates as $date) {
        echo "<td>" . (isset($counts[$date]) ? $counts[$date] : 0) . "</td>";
    }
    echo "</tr>";
}

?>
</table>

代码未经测试,因为我没有原始数组,所以可能存在错误。我只是希望这会给您一些新的启发。