计算评级系统的平均值

calculate the average for a rating system

我想计算评级系统的平均值,但我在 innodb 中有正常的 table,在 json 中有一个列,名称为:"reviews",结构为:

{"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...不是整数吗?星号为整数...
星=4
不是星号=“4”

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

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

<?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 数据,但更改了变量名称。我希望它很容易理解我的 code.Thanks.

中发生的事情
$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;

这应该有效。