简体   繁体   中英

Sum mysql array in PHP

I need sum up quantity items. I have a database query, I print values:

while ($row = mysqli_fetch_array($lista)) {
    echo $row['przedmiot'].":".$row['ilosc'].'<br>';
}

then I get this result:

item1:1
item1:3
item2:1
item1:3
item2:5

I need to add these values, I would like to get this result:

item1:7
item2:6

@Sascha's answer will work, but I'd suggest a different approach - instead of querying all these rows, transferring them from the database to your application and then having to loop over them in the code, let the database do the heavy lifting for you:

SELECT   przedmiot, SUM(ilosc)  AS ilosc
FROM     mytable
GROUP BY przedmiot

This should help:

$result=[];
while ($row = mysqli_fetch_array($lista)) {
    echo $row['przedmiot'].":".$row['ilosc'].'<br>';
    if (!array_key_exists ($result, $row['przedmiot'])) {
        $result[$row['przedmiot']] =  $row['ilosc'];
    } else {
        $result[$row['przedmiot']] +=  $row['ilosc'];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM