gpt4 book ai didi

php - 从 PHP 中的数组中获取连续输赢

转载 作者:行者123 更新时间:2023-12-02 17:40:21 24 4
gpt4 key购买 nike

使用以下代码,我分析了一支球队已经打过的所有比赛,并用结果创建了一个数组:

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 胜,因为最后两场比赛赢了,而之前的一场比赛没有赢。

最佳答案

$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.

关于php - 从 PHP 中的数组中获取连续输赢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686507/

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