如何在PHP中循环遍历一个数组,同时平均一个元素的值,并且只保留新平均的字段?

euoag5mw  于 2023-02-11  发布在  PHP
关注(0)|答案(2)|浏览(99)

我有包含每天存储的分数的数据库。我想平均每个用户每个月的分数。到目前为止,我有这个:
DB结构:

id | name    | tscore            | added 

int| string  | float(100 or less)| date(2014-01-01 16:34:22)

代码:

while($row = mysql_fetch_assoc($getChartData)){ // Data from MySQL
    $added_date = explode(' ',$row['added']); // Date formate 2014-01-01 16:34:22
    $chartData[] = array(
        'id'     => $row['name'],
        'tscore' => $row['tscore'],
        'added'  => $added_date[0] // Here I take the month only
    );
}
if($_POST['range'] == 'month'){
    foreach($chartData as $key => $value){
        $added = explode('-',$chartData[$key]['added']);
        $count = 1;
        foreach($chartData as $key2 => $value2){
            $added2 = explode('-',$chartData[$key2]['added']);
            if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){ // if user is the same and the month is the same, add the scores together, increment counter, and unset 2nd instance
                $chartData[$key]['tscore'] = ((float)$chartData[$key]['tscore'] + (float)$chartData[$key2]['tscore']);
                $count++;
                unset($chartData[$key2]);
            }     
        }
        $chartData[$key]['tscore'] = ($chartData[$key]['tscore']/$count); // Average all the scores for the month.
    }
}

问题是这个方法删除了$chartData数组的所有元素。我可以尝试解决这个问题吗?

1aaf6o9v

1aaf6o9v1#

你应该尝试用MySQL来解决这个问题。尝试类似这样的操作(用你的表名替换'your_scores_table'):

SELECT
    Score.name, 
    AVG(Score.tscore) AS `avg`,
    CONCAT(YEAR(Score.added), '-', MONTH(Score.added)) AS `year_month`
FROM 
    your_scores_table AS Score
GROUP BY 
    Score.name ASC, 
    YEAR(Score.added) DESC, 
    MONTH(Score.added) DESC
;
jgovgodb

jgovgodb2#

你的逻辑是错误的。你在同一个数组中循环了两次。这意味着下面的if总是计算为true这意味着数组项将总是被取消设置

//This will always be true
if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){

创建另一个数组来保存分数可能会更简单。

$aScores = array();
$count = 1;
foreach($chartData as $key => $value){

    //Add score to a different array
    $aScores[$value['name']]['tscore'] = (($aScores[$value['name']]['tscore'] + $value['tscore']) / $count);

    $count++;
}

我也会研究一下MySQL的AVG函数,你可以用它来保存你在PHP中做它

相关问题