Nested 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 work:

foreach ($league->teams->players as $player) {
    echo $player->name;


What am I missing? Do you need to use two foreach loops?


source to share

3 answers

See this example:


//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";








So these are three separate classes, not one class. You haven't shown anything about how you tie these classes together and how you actually create the data structure. I don't understand how you think you can magically enumerate all players with a call, for example $league->teams->players

, without having concrete methods in each class to handle aggregating data stored in nested objects.

Without defining these relationships in your classes, you would need to do nested loops like this:

foreach ($league->Teams as $team) {
    foreach($team->Players as $player) {
        echo $player->name;


If you need methods, such as a list of all players at the league level, you will need to define methods for this. Perhaps something like:

In the command class:

public function function get_all_players() {
    $return = array();
    if(count($this->Players) > 0) {
        $return = $this->Players;
    return $return;


In league class:

public function get_all_players() {
    $return = array();
    if(count($this->Teams) > 0) {
        foreach($this->Teams as $team) {
            $return = array_merge($return, $team->get_all_players());
    return $return;



foreach($league->get_all_players() as $player) {
    echo $player->name;




You may need two nested foreach

foreach ($league->teams as $team;){
  foreach ($team->players as $player){
    $list[] = $player->name;





All Articles