我有包含每天存储的分数的数据库。我想平均每个用户每个月的分数。到目前为止,我有这个:
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
数组的所有元素。我可以尝试解决这个问题吗?
2条答案
按热度按时间1aaf6o9v1#
你应该尝试用MySQL来解决这个问题。尝试类似这样的操作(用你的表名替换'your_scores_table'):
jgovgodb2#
你的逻辑是错误的。你在同一个数组中循环了两次。这意味着下面的
if
将总是计算为true这意味着数组项将总是被取消设置创建另一个数组来保存分数可能会更简单。
我也会研究一下MySQL的AVG函数,你可以用它来保存你在PHP中做它