I have a class that has this type of structure:
Class League
Array Teams
Class Teams
Array Players
Class Players
String name
However, if I want to get a list of all players in the league, this doesn't seem to work:
foreach ($league->teams->players as $player) {
echo $player->name;
}
What am I missing? Do you have to use two foreach loops?
See this example:
<?php
//Create your players
$player1 = new stdClass;
$player2 = new stdClass;
$player3 = new stdClass;
$player1->name = 'Mike';
$player2->name = 'Luke';
$player3->name = 'Smith';
//Create your teams
$team1 = new stdClass;
$team2 = new stdClass;
//Adding the players to their teams
$team1->Players = array($player1, $player2);
$team2->Players = array($player3);
//Create the league
$league = new stdClass;
//Adding the teams to the league
$league->Teams = array($team1, $team2);
//For each element in the Teams array get the team in $team
foreach ($league->Teams as $teams) {
//For each element in the Players array get the player in $player
foreach($teams->Players as $player) {
//Print the name
echo $player->name . "<br>\n";
}
}
?>
Output:
Mike
Luke
Smith
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With