2

This I believe is a little harder than the title makes it sound, but I could be completely wrong. I have an array like this:

[["londrina",15],["cascavel",34],["londrina",23],['tiradentes',34],['tiradentes',21]]

I want to be able to take the common values, in this case londrina and tiradentes, and add the numbers together. My PHP code is the following:

$qry = mysql_query("SELECT * FROM bap WHERE semana = '".$week."'");
    $rows = array();
    while($row = mysql_fetch_array($qry)) {
        $rows[] = $row;
    }

    $resultstr = array();

    foreach($rows as $row) {
        $resultstr[] = '["'.$row['zona'].'",'.$row['numero'].']';

    }
    $result = implode(', ',$resultstr);
    print '['.$result.']';

I'm not sure if any more info is needed. The array is being outputted in this format to use for a jquery json graphing plugin. Let me know if anymore info is needed.

2 Answers 2

4

Try this:

$arr = [["londrina",15],["cascavel",34],["londrina",23],['tiradentes',34],['tiradentes',21]];
$new_arr = [];

foreach ($arr as $a) {

    list($name, $num) = $a;

    if (!isset($new_arr[$name])) {
        $new_arr[$name] = 0;
    }

    $new_arr[$name] += $num;
}

var_dump($new_arr);

EDIT FOR OP

Use this code in its entirety, should give desired result:

$qry = mysql_query("SELECT * FROM bap WHERE semana = '".$week."'");

while ($row = mysql_fetch_array($qry)) {

    $rows[] = array($row['zona'], $row['numero']);
}

$new_arr = [];

foreach ($rows as $a) {

    list($name, $num) = $a;

    if (!isset($new_arr[$name])) {
        $new_arr[$name] = 0;
    }

    $new_arr[$name] += $num;
}

var_dump($new_arr);
Sign up to request clarification or add additional context in comments.

2 Comments

Haha, I guess I am, 2 minutes, never answered one so fast
This isn't working... The PHP code that I wrote outputs that array and trying to incorporate your code into mine is giving me the error Warning: Invalid argument supplied for foreach()
3
SELECT zona,
       SUM(numero) AS sum  
  FROM bap 
 WHERE semana = $week 
 GROUP BY zona

6 Comments

Saying Undefined index: numero
Is your column called numero? From the look of your code, it is; but if not then replace with the appropriate column that you want summing up
Yes, that is the collumns name
Then use sum in your PHP code instead, because that SQL aliases the sum of all related values of numero in a new temporary column called sum.... or change the alias to numero
Thanks! I figured out what was going wrong. Naming the column sum was screwing with the code, I just changed it to numero and everything worked. I didn't even know about the GROUP BY thing.
|

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.