Sum mysql array in PHP

Viewed 64

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
2 Answers

@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'];
    }
}
Related