多维数组中的求和值(选择多行的多个列)
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?
假设我有5个不同的列, 示例: strong> p>
用户有3个帖子,所以它会 在查询中选择3行。 p>
我想对 e.g。 p>
所以我需要将所有这些加起来得到15。 p>
我知道要使用 a,b,c,d,e code> ,我正在选择多行: p>
$ result = mysqli_query($ conn,“SELECT a,b,c,d,e FROM posts WHERE submitter ='$ user '“);
而($ row = mysqli_fetch_assoc($ result)){
$ ratings [] = $ row;
}
code> pre>
a code>(当然还有其余的)的所有行的值求和。 p>
第1行 code>
a code> value = 4 p>
第2行 code >
a code> value = 10 p>
第3行 code>
a code> value = 1 p>
\ n
array_sum($ ratings) code> 找到数组的总和但是只有当你选择一行(
a code>)时才能有多行,但由于选择了多个列值,这是多维的? p>
div>
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?