gpt4 book ai didi

php - 在 PHP 中嵌套 Foreach 循环

转载 作者:搜寻专家 更新时间:2023-10-31 21:07:34 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com