2017-10-15 75 views
0

我的產品相當於介質和全如何計算產品估值系統的正確百分比?

例的明星價值的系統:

0.5 - 1 - 1.5 - 2 - 2.5 - 3 - 3.5 - 4 - 4.5 - 5

我得到的數據正確地採取兩個數據一箇中等和整體和總和兩個值

從以下諮詢:

//we define in a variable the id of the product valued by the valuation system 
$id_product = 1; 

//we obtain an average and integer value equivalent to 4.5 and 5 
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(4.5,5)"); 
$stmt->bind_param("i",$id_product); 

$stmt->execute(); 
$stmt->bind_result($sum); 

while ($stmt->fetch()) { 
    echo $sum; 
} 

//we obtain an average and integer value equivalent to 3.5 and 4 
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(3.5,4)"); 
$stmt->bind_param("i",$id_product); 

$stmt->execute(); 
$stmt->bind_result($sum); 

while ($stmt->fetch()) { 
    echo $sum; 
} 

//we obtain an average and integer value equivalent to 2.5 and 3 
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(2.5,3)"); 
$stmt->bind_param("i",$id_product); 

$stmt->execute(); 
$stmt->bind_result($sum); 

while ($stmt->fetch()) { 
    echo $sum; 
} 

//we obtain an average and integer value equivalent to 1.5 and 2 
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(1.5,2)"); 
$stmt->bind_param("i",$id_product); 

$stmt->execute(); 
$stmt->bind_result($sum); 

while ($stmt->fetch()) { 
    echo $sum; 
} 

//we obtain an average and integer value equivalent to 0.5 and 1 
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(0.5,1)"); 
$stmt->bind_param("i",$id_product); 

$stmt->execute(); 
$stmt->bind_result($sum); 

while ($stmt->fetch()) { 
    echo $sum; 
} 

現在我的問題是如何能夠正確計算數據百分比和得到的結果像下面的圖片:

enter image description here

+0

'Sumo'?就像'摔角'一樣? – Strawberry

+0

@Strawberry不是那麼嚴重只有一個正確的錯誤可以說他的意思是「總和」 –

回答

1

中的百分比表格基於計數,而不是評分值的總和。

您可以在一個查詢中完成所有這些工作,您無需爲每個評估範圍單獨查詢。

$stmt = $con->prepare(' 
    SELECT SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star, 
      SUM(rating IN (3.5, 4))/COUNT(*)*100 AS pct_4_star, 
      SUM(rating IN (2.5, 3))/COUNT(*)*100 AS pct_3_star, 
      SUM(rating IN (1.5, 2))/COUNT(*)*100 AS pct_2_star, 
      SUM(rating IN (0.5, 1))/COUNT(*)*100 AS pct_1_star, 
      AVG(rating) AS avg_rating 
    FROM ratings 
    WHERE id_product = ?'); 
$stmt->bind_param('i', $id_product); 
$stmt->execute(); 
$percents = array(; 
$stmt->bind_result($percents[5], $percents[4], $percents[3], $percents[2], $percents[1], $avg_rating); 
if ($stmt->fetch()) { 
    for ($i in array(5, 4, 3, 2, 1)) { 
     echo "%i stars: " . round($percents[$i]) . "%<br>"; 
    } 
    echo "Average rating: $avg_rating<br>"; 
} else { 
    echo "This product is not yet rated<br>"; 
} 
+0

,並以這種方式如何顯示個人百分比作爲圖像即幾個客戶投票明星10%的客戶,例如 – Alex

+0

使條的長度取決於'pct _#_ star'。 – Barmar

+0

PHP具有圖像功能,可讓您創建特定大小的矩形。 – Barmar