Reputation: 1589
I have the following foreach loop that I'm getting good results with however when it gets to the elseif statement I'm attempting to see if two of the players are on the same team or not and if they are then have them listed together separated with a & symbol. Currently I am getting the following still.
Player 1 vs. Player 2 vs. Player 3 vs. Player 4
This is okay however Player 1 and Player 2 are on the same team. So its not seeing them as on the same team for some reason. Does someone see what my issue is?
@foreach ($match->players AS $key => $player)
@foreach ($player->list as $member)
{{ $member->player_name }}
@endforeach
@if($match->players->count() - 1 != $key)
vs.
@elseif ($match->players[$key - 1]->team_id == $player->team_id)
&
@endif
@endforeach
EDIT: I changed the data a little but still should work.
http://pastebin.com/AdyzemC4
Upvotes: 3
Views: 52590
Reputation: 419
It was tricky to puzzle together your $match variable :)
@if($match->players->count() - 1 != $key)
Your $match->players->count()
is always equal to the value of the number of players(say 'n'). So your 'if
' ONLY checks the 'n-1' != current key ($key
). [Which is true except for the last key, so you get all 'vs'].
This should work:
@foreach ($match->players AS $key => $player)
@foreach ($player->list as $member)
{{ $member->player_name }}
@endforeach
@if($player->team_id != $match->players[$key + 1]->team_id)
vs.
@elseif ($player->team_id == $match->players[$key + 1]->team_id)
&
@endif
@endforeach
In this we are checking if the current player's team is the same as the next player's team [$key+1
].
Note:
You need to stop the loop for the last player, since $key+1
will go outside your array and you will get an offset error.
Therefore add another if:
@foreach ($match->players AS $key => $player)
@foreach ($player->list as $member)
{{ $member->player_name }}
@endforeach
@if($key + 1 < $match->players->count())
@if($player->team_id != $match->players[$key + 1]->team_id)
vs.
@elseif ($player->team_id == $match->players[$key + 1]->team_id)
&
@endif
@endif
@endforeach
Upvotes: 5