0
votes

I have an array with two values, userID and a transaction value. The userID is NOT unique, and I would like a list/array of the same values, just "summed up". Meaning: If a userID has more occurrences, then I would like the 2nd value (the transaction) to be added together. I will post an example.

$a = array(
    1 => 1,
    1 => 2,
    2 => 3,
    2 => -17
);

The result after running whatever function is needed, is:

$a = array(
    1 => 3,
    2 => -14
);

So no duplicate userID's, and the transaction values are added to the one entry of the userID.

I am getting these values from a SQL database, so if I can solve this with a SQL view or something, that would also go as a valid answer :-)

3
such an array could not exist... if you assign a key twice, the second assignment will overwrite the first. as stated, your array would only contain 1 => 2, 2 => -17 with no dupes. - Marc B
If you're planning on retrieving data that would look like this from a database, use the database aggregation functions with a GROUP BY to achieve what you want in your SELECT statement - Mark Baker

3 Answers

3
votes

In sql if your columns are say, id and value, you could do

select sum(value) from table_name group by id
0
votes

Have a look at this

$array = array_unique($array);

function.array-unique

-2
votes
$a = array(
    1 => 1,
    1 => 2,
    2 => 3,
    2 => -17
);

$b = array_unique($a);