Reputation: 102
Everyone,
I am working an rating average value for every review and 4 fields (price,quality,support and delivery) of rating. From following function return wrong average value. It should return 2 but returning 1.
function review_rating_average($pid,$cid,$rid) {
$query = mysqli_query("SELECT rate_price, rate_quality, rate_support, rate_delivery FROM reviews WHERE (product_id = $pid and client_id = $cid and review_id = $rid)");
$array = array();
foreach($query as $row) {
$array[1] = 2;
$array[2] = 1;
$array[3] = 4;
$array[4] = 3;
}
$result = implode(", ", $array);
$stars = array($result);
foreach ($stars as $star) {
$rating[] = $star;
}
$average = array_sum($rating) / count($rating);
return $average;
}
Upvotes: 1
Views: 173
Reputation: 324750
Your code is... all kinds of wrong.
I mean aside from not actually using $query
(or $row
), I'll assume that's just for testing, just look at the rest of it...
// $array = [ , 2,1,4,3];
$result = implode(", ", $array);
// $result = "2, 1, 4, 3";
$stars = array($result);
// $stars = ["2, 1, 4, 3"];
foreach ($stars as $star) {
$rating[] = $star;
}
// $rating = ["2, 1, 4, 3"]; // foreach loop is a big no-op...
$average = array_sum($rating) / count($rating);
// $average = 2 (due to casting string to number) / 1 = 2
return $average;
It's a mess, none of it does what you mean for it to do.
Just do this:
fetch_row
on your $query
resultreturn array_sum($row) / count($row);
You don't even need to transform anything, your data from the database is already in perfect form to just be averaged!
Upvotes: 1