简体   繁体   English

计算数组中的出现次数

[英]Calculating number of occurrences in array

Consider the following print_r() of an array 考虑以下数组的print_r()

在此处输入图片说明

Problem 问题

There are 4 users who make predictions on the result of 3 matches in a tournament Calculate how many votes each team got. 有4位用户对锦标赛中3场比赛的结果进行预测。计算每支球队获得多少票。

PSEUDO 伪装

  • Each match should have a total of 4 votes (since 4 users are voting) 每场比赛总共应有4票(因为有4位用户在投票)
  • There are 3 outcomes HomeTeam Picked to win, AwayTeam Picked to win, Draw Picked 有3个结果被HomeTeam选中赢得,AwayTeam选中赢得了,平局被选中
  • Loop over array keep track of number of votes in each match for Home Team, Away Team, Draw. 循环遍历数组可跟踪主队,客队,平局各场比赛的票数。

    My Code to solve above problem 我的代码来解决上述问题

     foreach($results as $result){ $homeTeam = $result['homeTeam']; $awayTeam = $result['awayTeam']; $draw = 'Draw'; $pickedTeam = $result['pickedTeam']; $nrVotes = $result['nrVotes']; $gameID = $result['gameID']; //CHECK IF NEW MATCH OR SAME MATCH ON ITERATION if($gameID !== $newGameID) { if ($homeTeam === $pickedTeam) { $homeVotes = $nrVotes; //homeTeam Got 0 Votes if (!isset($homeVotes)) { $homeVotes = 0; } } if ($awayTeam === $pickedTeam) { $awayVotes = $nrVotes; //AWAY Team Got 0 Votes if (!isset($awayVotes)) { $awayVotes = 0; } } if ($pickedTeam === $draw) { $drawVotes = $nrVotes; //Draw Got Zero Votes if (!isset($drawVotes)) { $drawVotes = 0; } } echo $homeTeam . 'Number Of Votes = ' . $homeVotes; echo '<br />'; echo $awayTeam . 'Number Of Votes = ' . $awayVotes; echo '<br />'; echo $draw . ' Number Of Votes = ' . $drawVotes; } //CHECK FOR NEW MATCH $newGameID = $result['gameID']; }//foreach 

If been staring at the PC screen for a long time so Im not sure if it is a small logical error or if my approach is completely wrong, as im getting a weird output as can be seen on below screen shot: 如果长时间盯着PC屏幕,那么我不知道这是一个小逻辑错误还是我的方法完全错误,因为我得到了一个奇怪的输出,如下面的屏幕截图所示:

Code Output 代码输出 在此处输入图片说明

Notice how the number of draw votes seem to get correctly calculated but not the rest.... that is where my problem is, ive been stuck on if for hours 请注意,如何正确计算抽签数目,但其余部分却未正确计算.... 这就是我的问题所在,我已经坚持了好几个小时

Additional Info DB table 附加信息数据库表

在此处输入图片说明

Any help much appreciated. 任何帮助,不胜感激。

UPDATE MYSQL QUERY 更新MYSQL查询

$sql ='SELECT picks.*, schedule.homeTeam, schedule.awayTeam, schedule.gameID, picks.team, COUNT(*) AS number_of_picks
FROM picks
JOIN schedule ON picks.gameID = schedule.gameID
WHERE picks.tournament = :tournament AND picks.weekNum = :weekNum
GROUP BY schedule.gameID, picks.team
ORDER BY schedule.gameID, picks.team';

You have some issues in your code. 您的代码中有一些问题。 First of all, the logical mistake you made lies here: 首先,您犯的逻辑错误在于:

if($gameID !== $newGameID)

The if block will only be executed when the game ID changes, which of course only happens for the first entry for every game ID. if块仅在游戏ID更改时才执行,这当然只会在每个游戏ID的第一个条目中发生。 That's why only the draw votes are correct. 这就是为什么只有抽签才是正确的原因。

Then there are some variables that you have never declared (eg $newGameID ). 然后有一些您从未声明过的变量(例如$newGameID )。 This will yield a notice and is bad (even if you don't see it because display_errors is probably set to 0). 这将产生一个通知并且很糟糕(即使您没有看到它,因为display_errors可能设置为0)。

Furthermore, all your isset() s like here: 此外,您所有的isset()像这样:

$homeVotes = $nrVotes;
if (!isset($homeVotes)) {

are pretty useless as you're declaring the variable right before, so !isset() will always evaluate to false. 在您之前刚刚声明变量时,它几乎没有用,所以!isset()始终会得出false。

I'd personally go for an array in this situation and do something like this: 在这种情况下,我个人想去做一个数组,然后做这样的事情:

$arr = array();
$currentGameId = -1;
foreach($results as $result) {
    $gameId = $result['gameID'];
    $homeTeam = $result['homeTeam'];
    $awayTeam = $result['awayTeam'];
    $pickedTeam = $result['pickedTeam'];
    $nrVotes = $result['nrVotes'];

    // initialize new subarray if game id changes
    if ($gameId != $currentGameId) {
        $arr[$gameId]['homeVotes'] = 0;
        $arr[$gameId]['awayVotes'] = 0;
        $arr[$gameId]['drawVotes'] = 0;

        // remember current game id
        $currentGameId = $gameId;
    }

    // add votes
    if ($pickedTeam == $homeTeam) {
        $arr[$gameId]['homeVotes'] += $nrVotes;
    } elseif ($pickedTeam == $awayTeam) {
        $arr[$gameId]['awayVotes'] += $nrVotes;        
    } else {
        $arr[$gameId]['drawVotes'] += $nrVotes;
    }
}

This will give you an array with the game IDs as index like this: 这将为您提供一个以游戏ID作为索引的数组,如下所示:

Array
(
    [127] => Array
        (
            [homeVotes] => 2
            [awayVotes] => 0
            [drawVotes] => 2
        )

    [128] => Array
        (
            [homeVotes] => 2
            [awayVotes] => 1
            [drawVotes] => 1
        )

)

As billyonecan mentionned, your problem is 正如Billyonecan提到的,您的问题是

if($gameID !== $newGameID)

If you look at your array data, you'll notice that $results[0] is the first occurence of match 127 and it gives the amount of draw votes. 如果查看数组数据,您会注意到$ results [0]是第127个匹配项,它给出了抽签的数量。 Your if statement will make $results[1] and $results[2] be ignored. 您的if语句将使$ results [1]和$ results [2]被忽略。 The same thing happens with match 128 and so on. 匹配128等也会发生相同的情况。

The way around this is to declare your variables first, and every time you change game number, you echo your variables and then reset them (don't forget to use the information contained in this line or you'll be missing a value); 解决此问题的方法是先声明您的变量,并且每次更改游戏编号时,您都将回显您的变量,然后将其重置(不要忘记使用此行中包含的信息,否则您会丢失值);

Your code would look something like this: 您的代码如下所示:

<?php
function output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes){
    echo $homeTeam . ' Number Of Votes = ' . $homeVotes;
    echo '<br />';
    echo $awayTeam . ' Number Of Votes = ' . $awayVotes;
    echo '<br />';
    echo $draw . ' Number Of Votes = ' . $drawVotes;
    echo '<br />';
}

$results = array(
    0 => array('gameID' => '127','homeTeam' => 'Wales','awayTeam' => 'Scotland','pickedTeam' => 'Draw','nrVotes' => '3'),
    1 => array('gameID' => '127','homeTeam' => 'Wales','awayTeam' => 'Scotland','pickedTeam' => 'Wales','nrVotes' => '1'),
    2 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'Draw','nrVotes' => '1'),
    3 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'France','nrVotes' => '2'),
    4 => array('gameID' => '128','homeTeam' => 'France','awayTeam' => 'Ireland','pickedTeam' => 'Ireland','nrVotes' => '1')
);

$homeVotes = 0;
$awayVotes = 0;
$drawVotes = 0;
$newGameID = $results[0]['gameID'];

foreach($results as $result){
    $homeTeam = $result['homeTeam'];
    $awayTeam = $result['awayTeam'];
    $draw = 'Draw';
    $pickedTeam = $result['pickedTeam'];
    $nrVotes = $result['nrVotes'];
    $gameID = $result['gameID'];

    //CHECK IF NEW MATCH OR SAME MATCH ON ITERATION
    if($gameID !== $newGameID) {
        // New match, output and reset
        output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes);
        $homeVotes = 0;
        $awayVotes = 0;
        $drawVotes = 0;

        if ($homeTeam === $pickedTeam) {
            $homeVotes = $nrVotes;
            //homeTeam Got 0 Vote
            if (!isset($homeVotes)) {
                $homeVotes = 0;
            }
        }
        if ($awayTeam === $pickedTeam) {
            $awayVotes = $nrVotes;
            //AWAY Team Got 0 Votes
            if (!isset($awayVotes)) {
                $awayVotes = 0;
            }
        }
        if ($pickedTeam === $draw) {
            $drawVotes = $nrVotes;
            //Draw Got Zero Votes
            if (!isset($drawVotes)) {
                $drawVotes = 0;
            }
        }

    }

    else {
        // The same match

        if ($homeTeam === $pickedTeam) {
            $homeVotes = $nrVotes;
            //homeTeam Got 0 Vote
            if (!isset($homeVotes)) {
                $homeVotes = 0;
            }
        }
        if ($awayTeam === $pickedTeam) {
            $awayVotes = $nrVotes;
            //AWAY Team Got 0 Votes
            if (!isset($awayVotes)) {
                $awayVotes = 0;
            }
        }
        if ($pickedTeam === $draw) {
            $drawVotes = $nrVotes;
            //Draw Got Zero Votes
            if (!isset($drawVotes)) {
                $drawVotes = 0;
            }
        }
    }
    //CHECK FOR NEW MATCH
    $newGameID = $result['gameID'];
   }//foreach

   //This line outputs the last match which would not be output otherwise.
   output($homeTeam, $homeVotes, $awayTeam, $awayVotes, $draw, $drawVotes);
?>

The if statements that are used to update the values should be put into a function in order to avoid replicate code. 应该将用于更新值的if语句放入函数中,以避免重复代码。 Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM