计算评级系统的平均值

时间:2016-03-31 10:45:26

标签: php mysql rating

我想计算一个评级系统的平均值,但是我在innodb中有一个普通的表,在json中有一个名字的列:"评论"这种结构:

{"comments": 
    [
        {"name": "Jonh", "text": "nice phone", "star": 4}, 
        {"name": "igon", "text": "not good", "star": 2}, 
        {"name": "marco", "text": "i not like this", "star": 3},
        {"name": "david", "text": "good product", "stelle": 5}
    ]
}

现在我需要计算一般的恒星。 它是在sql还是在php中?在sql我不知道如何,在PHP我有查询问题只提取全明星,例如:

$reviews_nn = $rowprod["reviews"];
$reviews = json_decode($reviews_nn,true);
$max = 0;
$n = 0;
foreach ($reviews[comments][star] as $rate => $count) {
    echo 'Seen ', $count, ' ratings of ', $rate, "\n";
    $max += $rate * $count;
    $n += $count;
}
echo 'Average rating: ', $max / $n, "\n";

但结果是NAN ...不是整数?星号是整数...
star = 4
不是明星=" 4"

我希望你能帮助我......坦克!!!

2 个答案:

答案 0 :(得分:2)

您的代码根本不可理解,但我为您创建了一个示例,我认为它将有助于解决您的问题: -

<?php
$data = '{"comments": [{"name": "Jonh", "text": "nice phone", "star": 4}, {"name": "igon", "text": "not good", "star": 2}, {"name": "marco", "text": "i not like this", "star": 3}, {"name": "david", "text": "good product", "stelle": 5}]}'; // your json data

//$reviews_nn = $rowprod["reviews"]; // i don't get from where you are getting this
$reviews = json_decode($data,true); // decode the json data
$max = 0;
$n = count($reviews['comments']); // get the count of comments
echo "<pre/>";print_r($reviews); // print json decoded data
foreach ($reviews['comments'] as $rate => $count) { // iterate through array
$max = $max+$count['star'];
}
echo 'Average rating: ', $max / $n, "\n";
?>

输出: - https://eval.in/545582

注意: - 我已经获取了json数据,但更改了变量名称。我希望它很容易理解我的代码中发生了什么。谢谢。

答案 1 :(得分:0)

$reviews_nn = $rowprod["reviews"];
$reviews = json_decode($reviews_nn,true);
$numberOfReviews = 0;
$totalStars = 0;
foreach($reviews['comments'] as $review)
{
    $numberofReviews++;
    $totalStars += $review['star'];
}
$average = $totalStars/$numberOfReviews;
echo 'Average rating: '.$average;

这应该有用。