0

I have the following data in the following order(product_name -> stars):

Product 1 -> 5
Product 2 -> 4
Product 3 -> 3
Product 4 -> 2
Product 5 -> 3

Now, I want to calculate the average rating of each given rating. For eg: Average Rating of 5 stars and so on...

I tried the following for five stars:

$star = 0;
foreach($rates as $rate) { 
   $star = $star + $rate->stars 
}
$avg = $star / count($rates);
return $avg;

The result is 5. Now if I multiply it will 100, then it becomes 500%. I want it to be under 100%. Please help!

cske
  • 2,233
  • 4
  • 26
  • 24
Axel
  • 4,365
  • 11
  • 63
  • 122

2 Answers2

0

In PHP you can do this to get avg rating.

$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
          }
        ]

then you just need to add this

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;

I think this will help you.

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52
-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;
Mahdi Shad
  • 1,427
  • 1
  • 14
  • 23