通过以下代码,我分析了团队已经玩过的所有游戏并创建了一个包含结果的数组:
public function getResults($id) {
$array = array();
$scores = $this -> getAvailableScoresForTeam($id);
for ($i = 0; $i < count($scores); $i++) {
$homeTeam = $scores[$i]['homeTeam'];
$awayTeam = $scores[$i]['awayTeam'];
$homeScore = $scores[$i]['homeScore'];
$awayScore = $scores[$i]['awayScore'];
if ($homeTeam == $id && $homeScore > $awayScore) {
$array[$i] = "W";
}
elseif ($awayTeam == $id && $awayScore > $homeScore) {
$array[$i] = "W";
}
elseif ($homeTeam == $id && $homeScore < $awayScore) {
$array[$i] = "L";
}
elseif ($awayTeam == $id && $awayScore < $homeScore) {
$array[$i] = "L";
}
}
return $array;
}
例如,如果团队1总共玩了4场比赛,输掉了第一场比赛并赢得了最后3场比赛,那么第1队的阵列将是:(L, W, W, W)
我遇到的问题是决定输赢。使用上面的数组,我需要分析最后几个元素,看看它们是损失(“L”)还是赢(“W”),如果是,那么有多少。
对于输出,我只想尝试最新的输出。因此,对于(L, W, W, L, W, W)
,自从最后两场比赛获胜以来,它应该是2胜,之前的那场比赛不是。
答案 0 :(得分:6)
$arr = ["W", "L", "W", "W"]; //Definition
$arr = array_reverse($arr); //Reverse the array.
$last = array_shift($arr); //Shift takes out the first element, but we reversed it, so it's last.
$counter = 1; //Current streak;
foreach ($arr as $result) { //Iterate the array (backwords, since reversed)
if ($result != $last) break; //If streak breaks, break out of the loop
$counter++; //Won't be reached if broken
}
echo $counter; //Current streak.