[Solved] Retrieve array_sum from while ($stmt->fetch()) result

Hi all

Trying to get the ‘array_sum’ using a while prepared statement fetch result. Not sure how I can code the below so I turn the rating row into an array?

Everything works besides the array_sum, any ideas what I’m doing wrong?

while ($stmt->fetch()) {
    $rows[] = array('comments'=>$review_comments
        , 'subdir'=>$review_date
        , 'publisher'=>$review_publisher
        , 'rating'=>$review_rating);
    $avg = array_sum($rows['rating']) / count($rows['rating']);

Warning: array_sum() expects parameter 1 to be array, null given in…

I think I might need to some how put the rating into an array?


Yes, I think the problem is that you’re creating a two-dimensional array in $rows, so trying to pass in $rows['rating'] to anything wouldn’t end well - $rows['rating'] would probably give an error if you just echoed it, you’d need to access it as $rows[0]['rating'] and so on, specifying the second dimension. Also, would you want to calculate the value of $avg every time you fetch a new record, as you are doing there?

You’ve either got to create a separate array for the rating and continue to use array_sum, or write your own function to sum the specific element you need. Or total the rating as you run through the loop, and maintain a row count, and do the division afterward. Several ways to achieve it really.

$totalrating = 0;
$rowcount = 0;
while ($stmt->fetch()) {
    $rows[] = array('comments'=>$review_comments
        , 'subdir'=>$review_date
        , 'publisher'=>$review_publisher
        , 'rating'=>$review_rating);
    $totalrating += $review_rating;
$avg = $totalrating / $rowcount;

Perfect! :smile:
The code update runs great.

Thanks droopsnoot.

Just one issue, how do I return the result to 1 decimal?

Example, I’m currently seeing values like 1.625, 3.8333333333333 and so on, where I’d like to see 1.6, 3.8

Thanks, Barry

I was initially using the below inside my SQL query with a couple of INNER JOINS, though when I added this, things were not looping. I also read this can slow queries down and php was the best way of getting the avg result.

ROUND(AVG(r.rating), 1) AS ratingAVG

I’ve managed to reduce the value to 1 decimal place using:

$avg = round($totalrating / $rowcount, 1);

Cheers, Barry

That would do it, I think there’s quite a few ways of formatting the output.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.