计算评分系统的平均值

use*_*752 4 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}
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在我需要计算平均星级。它是在 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";
Run Code Online (Sandbox Code Playgroud)

但是结果是NAN...不是整数吗?它是星中的整数...
star=4
不是 star="4"

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

Ana*_*Die 5

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

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

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

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