计算评级系统的平均值


calculate the average for a rating system

我想计算评级系统的平均值,但我在innodb中有一个普通表,在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
not star="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数据,但更改了变量名。我希望它很容易理解我的代码中发生了什么。谢谢

$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;

这应该行得通。