【问题标题】:Get win/loss streak from an array in PHP从 PHP 中的数组中获取赢/输记录
【发布时间】:2014-02-10 19:46:44
【问题描述】:

使用以下代码,我分析了一个团队已经玩过的所有游戏,并使用结果创建了一个数组:

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

【问题讨论】:

  • 你想要所有的条纹,还是只想要最后一个/当前的?您可能想准确定义您要查找的输出。
  • 感谢您向我指出这一点!我马上加!

标签: php arrays


【解决方案1】:
$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.

【讨论】:

  • 感谢您的快速回答。我有一个问题:我如何确定连胜是赢还是输?
  • @DemCodeLines:这将是 $last 中的值。
猜你喜欢
  • 2022-01-17
  • 2017-11-04
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2012-07-05
  • 2016-01-29
相关资源
最近更新 更多