基于 php 数组字段创建新表


Create new table based on php array field

我有一个来自数据库查询的字段数组。

我想找到基于字段 $office_id 中的唯一值创建多个表的最佳解决方案。

所以基本上,我尝试使用 foreach 循环,存储office_id并每次检查循环是否唯一,然后关闭最后一个表 html,启动一个新的表 html 等。

我讨厌这个解决方案,因为这意味着数组必须按office_id排序,而且它非常丑陋。

任何人都可以建议使用更干净、更智能的代码来做到这一点的更好方法。我是否需要对阵列进行某种转换?有没有更好的方法来拉出独特的office_id领域?

我还想使用 office_id 作为每个表的标题,以便输出类似于以下内容:

office_id One
-----------------------------------
settle |  price |  Lister |  date  
-----------------------------------
       |        |         |
office_id Two
-----------------------------------
settle |  price |  Lister |  date  
-----------------------------------
       |        |         |

这就是我所拥有的(丑陋的),当我输入时,我意识到我错过了关闭标签:

<?php $thisOffice = ""; ?>  
<?php foreach ($fees as $fee): ?>
<?php if($thisOffice !== $fee->office_id) : ?>  
<table class="table table-striped table-condensed">
<tr>
<th>Settlement</th>
<th>Office</th>
<th>Price</th>
<th>Lister</th>
<th>Sold</th>
</tr>
<?php endif; ?>
<tr>
    <td> <?= $fee->settle_date ?></td>
    <td> <?= $fee->office_id ?></td>
    <td> <?= $fee->price ?></td>
    <td> <?= $fee->lister ?></td>
    <td> <?= $fee->sale_date ?></td>
</tr>
<?php $thisOffice = $fee->office_id; ?>
<?php endforeach; ?>

如果将数组拆分为三个维度,这将使您的生活更加轻松:

$offices[$id][] = $fee;

这样您就可以使用:

foreach ($offices as $id => $office) {
    foreach ($office as $fee) {
        // Build table
    }
}