-1

I am extracting some data from MySQL, then I am trying to sum up the values of the resulting array where the keys are the same. I have done this before just fine in this piece of code:

$q = "SELECT * FROM comenzi";
        $result = $odb->query($q);

        $sumArr = array();
        while($row = $result->fetch(PDO::FETCH_ASSOC)) {
            if ( !isset($sumArr[ $row['meniu_name'] ]) ) {
                $sumArr[ $row['meniu_name'] ] = $row['meniu_name'];
            }
            $sumArr[ $row['meniu_name'] ] += $row['cantitate'];
        }
        arsort($sumArr);
        $rowCount = 1;
        echo "<table><tr id='tableHeader'><td>#</td><td>produs</td><td>cantitate</td></tr>";
        foreach ($sumArr as $key => $value) {
            echo "<tr><td>" . $rowCount . "</td><td>" . $key . "</td><td>" . $value . "</td></tr>";
            $rowCount++;
        }
        echo "</table>";

That is my working example, which brings us to my next one that is somewhat similar, yet for some reason it does not yield the required results:

$q = "SELECT * FROM comenzi";
        $result = $odb->query($q);

        $sumArr = array();
        while($row = $result->fetch(PDO::FETCH_ASSOC)) {
            if ( !isset($sumArr[ $row['utilizator'] ]) ) {
                // $sumArr[ $row['utilizator'] ] = $row['utilizator'];
            }
            $sumArr[ $row['utilizator'] ] += $row['cantitate'];
        }
        arsort($sumArr);
        print_r($sumArr);
        $rowCount = 1;
        echo "<table><tr id='tableHeader'><td>#</td><td>utilizator</td><td>cantitate produse</td></tr>";
        foreach ($sumArr as $k => $v) {

            $odb                =           new PDO("mysql:host=".$host.";dbname=".$db, $user, $pass);

            $stmtCheck  =       $odb->prepare('SELECT nume, prenume, email, telefon FROM utilizatori WHERE id=?');
            $stmtCheck->execute(array($k));
            $r = $stmtCheck->fetch();


            echo "<tr><td>" . $rowCount . "</td><td>" . "<b>nume: </b>" . $r[0] . "<b> prenume: </b>" . $r[1] . "<b> email: </b>" . $r[2] . "<b> telefon: </b>" . $r[3] . "</td><td>" . $v . "</td></tr>";
            $rowCount++;
        }
        echo "</table>";

What happens here, is quite dubious: the commented line // $sumArr[ $row['utilizator'] ] = $row['utilizator'];, if it is commented out I get the expected results, however having it commented out I get the errors:

Notice: Undefined offset

If I do not comment that line I do not get the Undefined offset errors, but my values are ridiculous.

Correct values: Array ( [22] => 19 [32] => 11 )
Values with that line not commented out: Array ( [32] => 43 [22] => 41 )

I cannot even understand a mathematical way it gets to those values, can't find anything that could throw me the right direction, therefore I'm baffled.

5
  • Can't you just use array_sum($yourarray); ? Commented Nov 14, 2013 at 7:55
  • 1
    hmm, let me look into that really quick. Thanks for the tip! Commented Nov 14, 2013 at 8:04
  • looked into it: array_sum sums all the values inside that array, i need them to be summed key specific. That is why i use arsort($sumArr); Commented Nov 14, 2013 at 8:08
  • 2
    Why dont you use mysql to sum the same products? Take a look at GROUP BY tizag.com/mysqlTutorial/mysqlgroupby.php It will save you a lot of code! Commented Nov 14, 2013 at 8:36
  • @iffy: I apologise for the sharp tone you experienced on one of the answers here. The comments have been moderated away - don't let it put you off asking or answering questions. There are a few individuals on this site who, for all their technical know-how, are imo best ignored. Commented Nov 18, 2013 at 8:42

2 Answers 2

1

You just have to initialize your entry to 0 :

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    if(!isset($sumArr[ $row['utilizator'] ])) $sumArr[ $row['utilizator'] ] = 0;
    $sumArr[ $row['utilizator'] ] += $row['cantitate'];
}

The if line will create the $row['utilizator'] entry in the $sumArr array and will initialize its value to 0.

The problem you had is that you initialized it with a string I think :

$sumArr[ $row['meniu_name'] ] = $row['meniu_name'];

IMO $row['meniu_name'] is a string. Then, when you do addition on a string, PHP tends to convert this string into integer, which gives you weird results you noticed.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks mate. Much appreciated! if you could point me into the right direction to read around the subject so I understand why that is the case, would love long time.
0

You need to learn SQL first: as the listing below illustrates, you can do all of this in one query, which is both simpler and more efficient than trying to drag down all of the data and then process it.

SELECT nume, prenume, email, telefon, utilizator, sum(cantitate) 
FROM comenzi, utilizatori WHERE id = utilizator GROUP BY utilizator

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.