php - 在 PHP 中嵌套 Foreach 循环

标签 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 循环?

最佳答案

看这个例子:

<?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/

相关文章:

javascript - 使用 javascript 捕获数组并使用数组的值

php - WordPress - 生成帖子的 PDF

PHP7 给出错误 "PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/mysqli.so'

php - MySQL:选择列等于ID的行

java - 寻找设计模式

ios - Swift:创建具有不同自定义类型的数组

arrays - 快速更有效地搜索数组以匹配不同类型的方法

java - java中的随机数组值

python - 我是否正确使用 super() ?

vb.net - 如何使用 vb.net 创建输出将采用分层结构的父子集合