用循环对每组中的值求和


Sum values in each group with a loop

我有一个while循环,它给出了这个结果:

Userid      Point
1           10
1           15
2           5
2           10
3           8
3           2

如何首先将userid点数和最高数值的输出相加,如下所示:

Userid     Point
1          25
2          20
3          10

是否有任何"foreach","for"或任何其他方法可以完成此结果?

代码:

include ('variables.php');
//Fetch data from matchdata table
$q = "SELECT userid, matchid, homescore, awayscore FROM predictiondata ORDER BY userid ASC";
$r = mysqli_query($mysqli, $q);
while ($row = mysqli_fetch_array($r)) {
    //Define predictions
    $predhome = $row['homescore'];
    $predaway = $row['awayscore'];
    //Fetch gameresults
    $qres = "SELECT id, homescore, awayscore, bonuspoints FROM matches WHERE id = ".$row['matchid']."";
    $rres = mysqli_query($mysqli, $qres);
    $result = mysqli_fetch_array($rres);
    $homescore = $result['homescore'];
    $awayscore = $result['awayscore'];
    $bonus = $result['bonuspoints'];
    $id = $result['id'];

    //Calculate points
            if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $result_point = $correct_score + $correct_result + $correct_number + $correct_number; } 
            else if ($homescore == $predhome && $awayscore != $predaway OR $homescore != $predhome && $awayscore == $predaway) { $result_point = $correct_result + $correct_number; } 
            else if ($predhome > $predaway && $homescore > $awayscore OR $predhome < $predaway && $homescore < $awayscore) { $result_point = $correct_result; } 
            else if (is_null($predhome) OR $homescore == '') { $result_point = 0; } 
            else { $result_point = 0; }
            if ($homescore == $predhome && $awayscore == $predaway && $homescore != '') { $bonus = $bonus; } 
            else if (is_null($predhome) OR $homescore == '') { $bonus = 0;  } 
            else { $bonus = 0;  }
            if (is_null($predhome) OR $homescore == '') { $total_point = 0; } 
            else { $total_point = $result_point + $bonus; } 

            //Calculate total round sum
            $total_roundsum = $result_point + $bonus;
            //echo $username.' - '.$total_roundsum.'<br />';
    if($total_roundsum != 0) {
    echo $row['userid']. ' - ' .$total_roundsum.'<br />';
    }
}

目前,代码只回显结果。"variables.php"包含$correct_score + $correct_result + $correct_number变量。

假设这两列是一个相关联的数组——$users_and_points .

$points_array = array();
foreach ( $users_and_points as $user_id => $point ) {
    if( !isset( $points_array[$user_id] ) {
        $points_array[$user_id] = 0;
    }
    $points_array[$user_id] += $point;
}
// newly associated array with calculated totals
$points_array;

根据上面的代码构建一个包含用户和点的数组,而不是回显。

echo $row['userid']. ' - ' .$total_roundsum.'<br />';

可以替换为:

if( !isset( $points_array[$row['userid']] ) {
    $points_array[$row['userid']] = 0;
}
$points_array[$row['userid']] += $total_roundsum;

将为您提供一个用户id和关联点的关联数组。

print_r( $points_array );

注意:在循环之前设置变量。例如:$points_array = array();