0

Given these two arrays:

$first=array(
'books'=>1,
'videos'=>5,
'tapes'=>7,
);

$second=array(
'books'=>3,
'videos'=>2,
'radios'=>4,
'rc cars'=>3,
);

I would like to combine them so that I end up with

$third=array(
'books'=>4,
'videos'=>7,
'tapes'=>7,
'radios'=>4,
'rc cars'=>3,
);

I saw a function here: How to sum values of the array of the same key? but it looses the Key.

0

2 Answers 2

1

You can use something along the lines of:

function sum_associatve($arrays){
    $sum = array();
    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if (isset($sum[$key])) {
                $sum[$key] += $value;
            } else {
                $sum[$key] = $value;
            }
        }
    } 
    return $sum;
}
$third=sum_associatve(array($first,$second));
Sign up to request clarification or add additional context in comments.

4 Comments

I had tested the code before your edit, and it was working. Let me test your new code too.
You can also just use array_merge which would be a whole lot simpler! us2.php.net/array_merge
looks like that does the job. I'll turn it into a function.
array_merge() does not sum the values. For duplicate keys, it uses the value from the second array.
0

Just to be different... Uses func_get_args(), closures and enforces arguments to be arrays:

function sum_associative()
{
    $data = array();
    array_walk($args = func_get_args(), function (array $arg) use (&$data) {
        array_walk($arg, function ($value, $key) use (&$data) {
            if (isset($data[$key])) {
                $data[$key] += $value;
            } else {
                $data[$key] = $value;
            }
        });
    });

    return $data;
}

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.