我有一个具有这种结构的类:
Class League
Array Teams
Class Teams
Array Players
Class Players
String name
但是,如果我想获得联盟中所有球员的名单,这似乎行不通:
foreach ($league->teams->players as $player) {
echo $player->name;
}
我错过了什么?是否必须使用两个 foreach 循环?
最佳答案
看这个例子:
<?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
关于php - 在 PHP 中嵌套 Foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904882/