簡體   English   中英

計算評級系統的平均值

[英]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
不是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;

這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM