Hey everyone I’m struggling with a problem to display some data. I have two arrays of teams called rosterWhite and rosterBlack
On my view I have a table with two columns “White” and “Black”.
To illustrate, these are my teams int he Controller:
$rosterWhite=Roster::where([['match', '=', $id], ['team', '=', 'w']])->get(); $rosterBlack=Roster::where([['match', '=', $id], ['equipo', '=', 'b']])->get();
And this is my table in the view:
<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>
As you can see, the current implementation will go through the array creating a list of the nicknames inside a single cell and using line jumps.
+-------+-------+ | White | Black | +-------+-------+ | Wh1 | Bl1 | | Wh2 | Bl2 | | Wh3 | Bl3 | | Wh4 | Bl4 | | Wh5 | Bl5 | +-------+-------+
What I’m trying to figure out is how can I iterate through arrays, but instead of filling in everything in a single cell, that each name is a row.
something like this:
+-------+-------+ | White | Black | +-------+-------+ | Wh1 | Bl1 | +-------+-------+ | Wh2 | Bl2 | +-------+-------+ | Wh3 | Bl3 | +-------+-------+ | Wh4 | Bl4 | +-------+-------+ | Wh5 | Bl5 | +-------+-------+
Iterating outside of the TD, creates the list horizontally. So each name in a single cell but all names from both teams in the same row.
I can’t find a way to iterate through white list, and add cells under White column, then iterate through black list and add names under Black column.
Any tips for this? Maybe I should create two different tables that are somehow connected? thanks!
Advertisement
Answer
You could try something like this:
In your controller:
$rosterWhite=Roster::where([['match', '=', $id], ['team', '=', 'w']])->get(); $rosterBlack=Roster::where([['match', '=', $id], ['equipo', '=', 'b']])->get(); $maxCount = max($rosterWhite->count(), $roasterBlack->count());
In your view:
... <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>
And if you want to replace the @if
condition checking array key existence, you could easily do this:
<td class="text-center"> {{ $rosterWhite[$i]->nickname ?? "" }} </td>