'PHP - Calculate Average Rating Not Working?

I've been working on a movie review website and I can't quite get the calculate average rating functionality working. In the code below, In the first instance I am grabbing the current rating of the movie [$totalRating] via an API and setting the counter [$numRatings]. Then via an API I am collecting all of the ratings of that movie, attempting to to add them to the total rating, updating the counter within the loop.

However, when I rate movies they simply are updated to the registered rating (say I input an 8 it becomes an 8) and the division never takes place. Was wondering if anyone has any solutions or can see where I am going wrong?

function setUserRating($movieID)
{
    $ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
    $response = file_get_contents($ep);
    $Movies = json_decode($response, true);
    $baseRating = $Movies[0]['movieRating'];
    $numRatings = 1;
    $totalRating = $baseRating;


    $ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
    $resp = file_get_contents($ep);
    $userRatings = json_decode($resp, true);
    if (isset($userRatings['movie_ratings'])) {
        $reviews = $userRatings['movie_ratings'];
    }
    if (isset($reviews)) {
        foreach ($reviews as $row) {
            $numRatings++;
            $totalRating = $totalRating + $row['rating'];
        }
    }
    $avgUserRating = $totalRating / $numRatings;
    return $avgUserRating;
}
php


Solution 1:[1]

Might just need a small adjustment

function setUserRating($movieID)
{
    $ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
    $response = file_get_contents($ep);
    $Movies = json_decode($response, true);
    $baseRating = $Movies[0]['movieRating'];
    $numRatings = 0; //1
    $totalRating = 0; //$baseRating;

    $ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
    $resp = file_get_contents($ep);
    $userRatings = json_decode($resp, true);
    if (array_key_exists($userRatings['movie_ratings'])) {
        $reviews = $userRatings['movie_ratings'];
    }
    if (isset($reviews)) {
        foreach ($reviews as $row) {
            ++$numRatings;
            $totalRating += $row['rating'];
        }
    }

    return $numRatings > 0 ? $totalRating / $numRatings : $baseRating;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guido Faecke