在PHP中嵌套Foreach循环

时间:2015-04-27 20:01:10

标签: php arrays oop multidimensional-array foreach

我有一个具有这种结构的类:

Class League
    Array Teams

Class Teams
    Array Players

Class Players
    String name

但是,如果我想获得联盟中所有球员的名单,这似乎不起作用:

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

我错过了什么?你必须使用两个foreach循环吗?

3 个答案:

答案 0 :(得分:1)

见这个例子:

<?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";
  }
}

?>

输出:

Mike
Luke
Smith

答案 1 :(得分:1)

所以这些是三个独立的类,而不是一个类。您没有展示如何将这些类关联在一起以及如何实际创建数据结构。我不认为你怎么能够神奇地能够通过max-length之类的呼叫列出所有玩家,而无需在每个类中使用特定方法来处理嵌套对象中存储的数据的聚合。

如果没有在类中定义这些关系,则需要执行如下的嵌套循环:

$league->teams->players

如果你想要方法,例如列出联盟级别的所有玩家,你需要定义一个方法来做到这一点。也许是这样的事情:

在团队课程中:

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

在联赛课程中:

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

用法是:

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;
}

答案 2 :(得分:0)

您可能需要两个嵌套foreach

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

   }
}