我具有以下数据,按以下顺序排列(product_name-> stars):
Product 1 -> 5
Product 2 -> 4
Product 3 -> 3
Product 4 -> 2
Product 5 -> 3
现在,我想计算每个给定评分的平均评分。例如:5星的平均评分,等等...
我尝试了以下五颗星:
$star = 0;
foreach($rates as $rate) {
$star = $star + $rate->stars
}
$avg = $star / count($rates);
return $avg;
结果为5。现在,如果我将其乘以100,则它将变为500%
。我希望它低于100%。请帮忙!
答案 0 :(得分:0)
在PHP中,您可以执行此操作以获取平均评级。
$ratings = array:4 [▼
0 => {#128 ▼
+"product_name": "P1"
+"stars": 5
}
1 => {#129 ▼
+"product_name": "P2"
+"stars": 3
}
2 => {#130 ▼
+"product_name": "P3"
+"stars": 2
}
3 => {#131 ▼
+"product_name": "P4"
+"stars": 4
}
]
然后您只需添加此
function getStars($v) {
return $v->stars;
}
$ratings = array_map("getStars",$rates);
$score_count = count($ratings);
$score_sum = array_sum($ratings);
$mean_average = $score_sum / $score_count;
var_dump($mean_average);exit;
我认为这会对您有所帮助。
答案 1 :(得分:-1)
$star5 = $star4 = $star3 = $star2 = $star1 = 0;
foreach($rates as $rate) {
switch ($rate->stars) {
case 1:
$star1++;
break;
case 2:
$star2++;
break;
case 3:
$star3++;
break;
case 4:
$star4++;
break;
case 5:
$star5++;
break;
}
}
$percent1 = ($star1 / count($rates)) * 100; // percent
return $percent1;