如何在php/lavel中用不同的foreach迭代填充表中的两列



大家好,我正在努力解决显示一些数据的问题。我有两个团队阵列,称为名册白色名单黑色

在我看来,我有一张有两列的桌子";白色";以及";黑色";。

举例来说,这些是我的团队内部控制器:

$rosterWhite=Roster::where([['match', '=', $id], ['team', '=', 'w']])->get();
$rosterBlack=Roster::where([['match', '=', $id], ['equipo', '=', 'b']])->get();

这是我在视图中的表格:

<table class="table table-bordered" id="rosterTable" width="100%" cellspacing="0">
<thead>
<tr>
<th class="text-center">White</th>
<th class="text-center">Black</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">
@foreach ($rosterWhite as $whitePlayer)
{{ $whitePlayer->nickname }} <br>
@endforeach
</td>
<td class="text-center">
@foreach ($rosterBlack as $blackPlayer)
{{ $blackPlayer->nickname }} <br>
@endforeach
</td>
</tr>
</tbody>
</table>

正如您所看到的,当前实现将遍历数组,在单个单元格内创建一个昵称列表,并使用换行。

+-------+-------+
| White | Black |
+-------+-------+
|  Wh1  |  Bl1  |
|  Wh2  |  Bl2  |
|  Wh3  |  Bl3  |
|  Wh4  |  Bl4  |
|  Wh5  |  Bl5  |
+-------+-------+

我想弄清楚的是,我如何在数组中迭代,但不是在一个单元格中填充所有内容,而是每个名称都是一行。

像这样的东西:

+-------+-------+
| White | Black |
+-------+-------+
|  Wh1  |  Bl1  |
+-------+-------+
|  Wh2  |  Bl2  |
+-------+-------+
|  Wh3  |  Bl3  |
+-------+-------+
|  Wh4  |  Bl4  |
+-------+-------+
|  Wh5  |  Bl5  |
+-------+-------+

在TD之外循环,水平创建列表。因此,每个名字都在一个单元格中,但来自同一行的两个团队的所有名字。

我找不到一种方法来遍历白名单,在白列下添加单元格,然后遍历黑名单,在黑列下添加名称。

对此有什么建议吗?也许我应该创建两个以某种方式连接的不同表?谢谢

你可以试试这样的东西:

在您的控制器中:

$rosterWhite=Roster::where([['match', '=', $id], ['team', '=', 'w']])->get();
$rosterBlack=Roster::where([['match', '=', $id], ['equipo', '=', 'b']])->get();
$maxCount = max($rosterWhite->count(), $roasterBlack->count());

在您看来:

...
<tbody>
@for($i=0;$i<$maxCount;$i++)
<tr>
<td class="text-center"> 
@if( Arr::exists($rosterWhite, $i) ) 
{{ $rosterWhite[$i]->nickname }} 
@endif
</td>
<td class="text-center"> 
@if( Arr::exists($rosterBlack, $i) )
{{ $rosterBlack[$i]->nickname }} 
@endif 
</td>
</tr>
@endfor
</tbody>

如果你想替换@if条件检查数组密钥的存在,你可以很容易地做到这一点:

<td class="text-center"> 
{{ $rosterWhite[$i]->nickname ?? "" }} 
</td>

最新更新