2

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 2

4

@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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.