dongteng2534 2014-02-10 19:46
浏览 56
已采纳

从PHP中的数组中获取连胜

With the following code, I analyze all the games that a team has played yet and create an array with the results:

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;
}

For example, if the team 1 played 4 total games, lost the first one and won the last 3, then the array for team 1 would be: (L, W, W, W)

What I am having trouble with is determining the win/loss streak. With the array above, I need to analyze the last couple of elements and see if they were losses ("L") or wins ("W") and if so, then how many.

For the output, I am only trying to get the most recent one. So for (L, W, W, L, W, W), it should be 2 wins since the last two games were won and the one before that wasn't.

  • 写回答

1条回答 默认 最新

  • duanpo6079 2014-02-10 19:52
    关注
    $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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化