多维数组中的求和值(选择多行的多个列)

Let's say I have 5 different columns, a, b, c, d, e, and I'm selecting multiple rows:

$result = mysqli_query($conn,"SELECT a,b,c,d,e FROM posts WHERE submitter='$user'");

while ($row = mysqli_fetch_assoc($result)){
  $ratings[] = $row; 
}

Example:

The user has 3 posts, so it'll select 3 rows in the query.

I want to sum all of the rows' values for a (and the rest of course).

e.g.

row 1 a value = 4

row 2 a value = 10

row 3 a value = 1

So I need to sum all of those to get 15.


I know to use array_sum($ratings) to find the sum of the array but only if you select one column (a) which can have multiple rows, but this is multi-dimensional right due to multiple column values being selected?

You can just use sum in your query:

select sum(a)
     , sum(b)
     , sum(c)
     , sum(d)
     , sum(e)
from posts
where submitter = '$user'

You can use count aggregate function and group by in MySQL.

SELECT
  submitter,
  count(a) as rating
FROM posts
WHERE submitter='$user'
GROUP BY submitter

A a result you will get something like that:

some submitter, 3
another submitter, 10
one more submitter, 1

Is this helpful?