Calculate average from array with fmod()
I have a ratings array in which there are list of ratings of particular product from where i want the result to be average rating.
What i want to achieve is if average rating is 4.2 or 4.3 or something in between 4 to 4.5 it should result as 4.5 and if average rating is like 4.6 or 4.7 or something it should result as 5 rating.
I have done below stuff which is resulting 4.5 still if average rating os 4.2 or 4.6.
$product_ratings = Array
(
[0] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 5
[user_id] => 154
)
[1] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 5
[user_id] => 154
)
[2] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 3.5
[user_id] => 154
)
[3] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 5
[user_id] => 154
)
[4] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 2.5
[user_id] => 154
)
[5] => stdClass Object
(
[id] => 93
[product_id] => 5
[rating] => 4.5
[user_id] => 154
)
)
$r = 0;
$rating_total="";
foreach ($product_ratings as $row) {
$rating_total += $row->rating;
$r++;
}
$average_rating = "";
if($rating_total != "" || $rating_total != 0)
{
$average_rating = $rating_total / $r;
}
else
{
$average_rating = 0;
}
$avg_rating = $average_rating - fmod($average_rating, 0.5);
echo $avg_rating
from Laravel Questions and Answers https://laravelquestions.com/php/calculate-average-from-array-with-fmod/
via Lzo Media
No comments:
Post a Comment