Question

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.

Was it helpful?

Solution

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));

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top