我有很多棒球队,每个棒球队里都有一系列赛季。每个赛季内的获胜次数。我想统计一个团队的所有胜利,然后将此数字推入每个团队的数据中。我的最终目标是按照每个团队的总获胜次数来排序此主阵列。
我的问题是,我不知道如何将totalGamesWon统计信息推向团队数据的主要数组。
对于效率低下的编码,请提前致歉!如果有像我这样的新手有更好的方法可以做到这一点,那么我无所不能!
$teams = array(
array (
'teamName' => 'Yankees',
'seasons' => array (
array(
'seasonName' => '2018 Regular Season',
'wins' => 100
),
array(
'seasonName' => '2018 Playoffs',
'wins' => 2
)
)
),
array (
'teamName' => 'Red Sox',
'seasons' => array (
array(
'seasonName' => '2018 Regular Season',
'wins' => 108
),
array(
'seasonName' => '2018 Playoffs',
'wins' => 11
)
)
),
);
foreach ($teams as $team) {
$totalGamesWon = 0;
foreach ($team['seasons'] as $season) {
$totalGamesWon += $season['wins'];
}
$team['totalGamesWon'] = $totalGamesWon;
}
echo $teams[0]['teamName']; // outputs "Yankees"
echo $teams[0]['totalGamesWon']; // should output "102". Instead, I get "Notice: Undefined index: totalGamesWon"
只需更改$team
为&$team
,即可通过$team
按引用而不是按值传递:
foreach ($teams as &$team) {
$totalGamesWon = 0;
foreach ($team['seasons'] as $season) {
$totalGamesWon += $season['wins'];
}
$team['totalGamesWon'] = $totalGamesWon;
}
默认情况下($team
)它通过值传递,这意味着它仅在范围内(在循环中)更改。因此,每次迭代都会设置$ team ['totalGameswon']的值,但实际的数组$ teams不会受到影响。
通过引用传递它时,当前已更改的项目($team['totalGamesWon']
)会更改实际数组中的值。
因此:(按值传递)
foreach ($teams as $key => $team) {
$totalGamesWon = 0;
foreach ($team['seasons'] as $season) {
$totalGamesWon += $season['wins'];
}
$teams[$key]['totalGamesWon'] = $totalGamesWon;
}
和(通过引用传递)
foreach ($teams as &$team) {
$totalGamesWon = 0;
foreach ($team['seasons'] as $season) {
$totalGamesWon += $season['wins'];
}
$team['totalGamesWon'] = $totalGamesWon;
}
会给你同样的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句