Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting Foreach Loops in PHP

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?

like image 516
Paka Avatar asked Aug 05 '26 13:08

Paka


1 Answers

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
like image 80
Adrian Cid Almaguer Avatar answered Aug 08 '26 01:08

Adrian Cid Almaguer