我有以下多维数组:
Array
(
[0] => Array
(
[0] => Array
(
[name] => team0
[games] => Array
(
[0] => 3
)
)
[1] => Array
(
[name] => team1
[games] => Array
(
[0] => 2
)
)
[2] => Array
(
[name] => team2
[games] => Array
(
[0] => 1
)
)
[3] => Array
(
[name] => team3
[games] => Array
(
[0] => 0
)
)
)
我试图遍历数组并将数组中的信息存储在各个变量中,以使用这些变量作为参数对数据库执行查询。我发现使用这个多维数组很困惑,我很难理解如何正确迭代数组。事实上,这是我的代码......在这个阶段,我更多的是干涉foreach循环,试图更好地理解如何实现我需要做的事情。在每个团队名称" Array"之后,这个代码存在问题。也得到了回应。
foreach ($arrTeam as $array)
foreach ($array as $groupid => $group){
$in_groupID = $groupid+1;
foreach ($group as $name) {
if (isset($name)) echo $name.'<br>';
}
}
基本上我想要做的是从数组中获取groupid和teamname,将它们存储在$in_groupID
和$in_teamName
中,然后深入到数组中并抓住每个特定团队的游戏一次一个游戏 - 为我抓取的每个游戏在数据库上执行查询。查询本身不是问题,它以我想要的方式迭代这个令人困惑的循环,并将值存储为执行的参数。
任何帮助都将受到重视。正如我所说的,我并不关心执行数据库查询等等,我可以轻松地修复它并在以后添加它,我只需要知道如何从循环中存储参数来执行。
非常感谢您的帮助。
答案 0 :(得分:1)
当您遍历团队数组时,您将能够访问name
和games
数组。您不需要遍历每个团队,因为您知道每个团队的密钥。您需要迭代的是每个团队的所有游戏:
foreach($teams as $teamId => $team) {
// team id is in $teamId
$teamName = $team['name'];
// Iterate through the games
foreach($team['games'] as $number) {
// The game number (or id, or whatever you call it) is in $number
}
}
答案 1 :(得分:1)
foreach ($someInitArr as $rootIndex => $arrTeam)
foreach ($arrTeam as $teamid => $team) {
$teamName = $team['name'];
$teamID = $teamid + 1;
foreach($team['games'] as $gameNumber => $gameValue)
// here yo can grab each game separately within the database already having $teamName and $teamID
}