我在循环数组时遇到问题,让每个球队在最近10场比赛中得分。这就是我循环遍历这个数组的方式:
$WarzoneLast10MatchesTeamScore = [];
foreach($warzoneLast10matches->Results->Teams as $idx => $stats){
$WarzoneLast10MatchesTeamScore[$idx]['Score'] = $stats->Score;
$WarzoneLast10MatchesTeamScore[$idx]['Id'] = $stats->Id;
}
这个问题是它会给我一个错误,因为我试图获得最后10场比赛,所以结果必须是Result [0],Result [1],依此类推。 这就是我的意思:
+"Results": array:10 [▼
0 => {#17371 ▼
+"Links": {#13129 ▶}
+"Id": {#13130 ▶}
+"HopperId": "0e39ead4-383b-4452-bbd4-babb7becd82e"
+"MapId": "c89dae21-f206-11e4-a1c2-24be05e24f7e"
+"MapVariant": {#13121 ▶}
+"GameBaseVariantId": "42f97cca-2cb4-497a-a0fd-ceef1ba46bcc"
+"GameVariant": {#17372 ▶}
+"MatchDuration": "PT6M50.2813116S"
+"MatchCompletedDate": {#17367 ▶}
+"Teams": array:2 [▼
0 => {#17374 ▼
+"Id": 0
+"Score": 1
+"Rank": 1
}
1 => {#17375 ▼
+"Id": 1
+"Score": 0
+"Rank": 2
}
]
+"Players": array:1 [▶]
+"IsTeamGame": true
+"SeasonId": null
+"MatchCompletedDateFidelity": 1
}
1 => {#17378 ▶}
2 => {#17390 ▶}
3 => {#17402 ▶}
4 => {#17414 ▶}
5 => {#17426 ▶}
6 => {#17438 ▶}
7 => {#17450 ▶}
8 => {#17462 ▶}
9 => {#17474 ▶}
]
我显然不想为每个游戏制作10个循环,然后在我的视图中对每个游戏的分数进行硬编码。 如何循环结果对象,然后获取Teams->得分和Teams-> Id对象?
FYI 我知道我可以使用这样的集合:
public function getWarzoneLast10Matches($warzoneLast10matches) {
// Collect al the results for this array
$results = collect($warzoneLast10matches->Results);
$array = $results->map(function($item, $key) {
return [
'Gamertag' => $item->Players[0]->Player->Gamertag,
'MapId' => $item->MapId,
'GameBaseVariantId' => $item->GameBaseVariantId,
'Score' => $item->Teams[0]->Score,
'Score2' => $item->Teams[1]->Score,
'Id' => $item->Teams[0]->Id,
'Id2' => $item->Teams[1]->Id,
];
});
return $array;
}
但这不起作用,因为在某些游戏中只有一个团队,如果发生这种情况,那么它会给我一个错误,说明未定义的偏移1,因为没有团队2.我使用的另一种方法顶部不会给我错误。