如何以表格格式显示一组数据?

时间:2019-01-03 04:44:29

标签: php laravel

我有一个要以表格格式显示的数组。

我的桌子应该这样显示

Dept: Dept 1
No     Name    BankCode      Amount
1.     Name4   656789        119.20

Dept: Dept 2
No     Name    BankCode      Amount
1.     Name 1  DREW1CF       2775.24
2.     Name 2  DREW1CF       907.28
3.     Name 3  EWDR1CF       318.60

这是我的数组

array:38 [▼
  0 => {#389 ▼
    +"FullName": "Name 1"
    +"BankCode": "DREW1CF"
    +"EntityName": "Dept 2"
    +"amount": "2775.24"
  }
  1 => {#391 ▼
    +"FullName": "Name 2"
    +"BankCode": "DREW1CF"
    +"EntityName": "Dept 2"
    +"amount": "907.28"
  }
  2 => {#392 ▼
    +"FullName": "Name 3"
    +"BankCode": "EWDR1CF"
    +"EntityName": "Dept 2"
    +"amount": "318.60"
  }
  3 => {#393 ▼
    +"FullName": "Name 4"
    +"BankCode": "656789"
    +"EntityName": "Dept 1"
    +"amount": "119.20"
  }
  4 => {#394 ▶}
  5 => {#395 ▶}
  .....and so on
]

Laravel框架中的代码。

目前,我坚持使用我的foreach。

如果我像下面那样做,它将不会像我需要的那样显示。

我怎样才能实现foreach成为我所需要的?

我在foreach中不是很好,尤其是$ key => $ value。

@php
$i = 1;
@endphp
@foreach ($getClaim as $claims)
<tr>
  <td>@php
      echo $i++
      @endphp</td>
  <td>{{$claims->FullName}}</td>
  <td>{{$claims->BankCode}}</td>
  <td>{{number_format($claims->amount, 2, '.', ',')}}</td>
</tr>
@endforeach

1 个答案:

答案 0 :(得分:2)

在创建表之前对数据进行分组:

$groupedClaims = array_reduce($claims, function ($groups, $item) {
    if ($group = data_get($groups, $item->EntityName)) {
        // Using the spread operator
        data_set($groups, $item->EntityName, [ $item, ...$group ]);
        // Using array merge
        data_set($groups, $item->EntityName, array_merge($group, [$item]));
    } else {
        data_set($groups, $item->EntityName, [ $item ]);
    }
    return $groups;
}, []);

然后在您的视图文件中:

@foreach ($groupedClaims as $dept => $claims)
    <tr>
        <td colspan="4">Dept: {{ $dept }}</td>
    </tr>
    <tr>
        <td>No</td>
        <td>Name</td>
        <td>BankCode</td>
        <td>Amount</td>
    </tr>
    @foreach ($claims as $idx => $claim)
    <tr>
        <td>{{ $idx }}</td>
        <td>{{ optional($claim)->FullName ?? 'No FullName' }}</td>
        <td>{{ optional($claim)->BankCode ?? 'No BankCode' }}</td>
        <td>{{ number_format(optional($claim)->amount ?? 0, 2, '.', ',') }}</td>
    </tr>
    @endforeach
@endforeach