问题描述
我被困在这里。希望有人能帮忙。我有一个数据库,可以存储任何项目上已完成购买的用户。
这是我在树枝上的桌子
<table datatable [dtOptions]="dtOptions" class="row-border hover">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let arrayData of lspOverAllInfoArray">
<td> <tbody>
{% for paid_log in paid_logs %}
{% paid_log.user_id == user.id and paid_log.status == 2 %}
<tr>
<td>{{paid_log.project.name }}</td>
<td>{{paid_log.amount }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</td>
<td>Foo</td>
<td>Bar</td>
</tr>
</tbody>
</table>
结果
|Project ID| Purchase Amount|
1 |1000
1 |1010
2 |2111
4 |9954
1 |9871
4 |6121
我想遍历数据库并在项目ID相同的情况下总结购买金额?
期待这样的事情:
Project ID |Purchase Total
1 |11881
2 |2111
4 |16075
解决方法
尽管有可能,但Twig对于进行这样的计算并不理想。代码变得非常混乱。相反,我建议在定义onStart()
的{{1}}中创建数据结构。
示例:
paid_logs
然后,在您的Twig中,您可以简化:
function onStart()
{
// ... define $paid_logs and $user
$data = [];
foreach ($paid_logs as $paid_log) {
if ($paid_log->user_id == $user->id && $paid_log->status == 2) {
if (!isset($data[$paid_log->project_id])) {
$data[$paid_log->project->id] = 0;
}
$data[$paid_log->project->id] += $paid_log->amount;
}
}
$this['data'] = $data;
}