0

Possible Duplicate:
PHP Array_Sum on multi dimensional array

I am having a two dimesional array as follows.

array(
    (int) 0 => array(
        'Chrome' => '10',
        'Firefox' => '3',
        'Internet Explorer' => '1',
        'Safari' => '1',
        'Mobile' => (int) 0,
        'Others' => (int) 0
    ),
    (int) 1 => array(
        'Chrome' => '5',
        'Firefox' => '2',
        'Safari' => '2',
        'Internet Explorer' => '1',
        'Opera' => '1',
        'Mobile' => (int) 0,
        'Others' => (int) 0
    )
)

I want to add values for same keys and get it into single array as follows.

array(
    'Chrome' => '15',
    'Firefox' => '5',
    'Internet Explorer' => '2',
    'Safari' => '3',
    'Opera' => '1',
    'Mobile' => '0'
    'Others' => '0'
)

Please give me solution for this.

Community
  • 1
  • 1
Sanganabasu
  • 943
  • 7
  • 21
  • 39
  • possible duplicate of [PHP Array_Sum on multi dimensional array](http://stackoverflow.com/q/1404422/) – outis Jul 19 '12 at 06:57
  • 2
    [What have you tried?](http://whathaveyoutried.com). While "please give me the solution" is polite, it's the bad kind of lazy. If you're ever to have any hope of being a competent developer, you're going to need to learn how to figure things out, rather than relying on others for everything. Instead of asking for the final step, state which step you are on and ask for help getting to the next step. It's also not what SO is about; SO is for questions about problems with specific code. If you need help with design, try [programmers.SE](http://programmers.stackexchange.com/). – outis Jul 19 '12 at 07:01

1 Answers1

3

Iterate over the sub-arrays and take over key and value pairs. In case they exist, add the value (integer arithmetical sum operation) to the existing value.

When you are done with iterating the sub-arrays, the result is ready.

$array = array();
foreach ($subArrays as $subArray)
{
    foreach ($subArray as $key => $value)
    {
        isset($array[$key]) || $array[$key] = 0;
        $array[$key] += (int) $value;
    }
}

// ready, but make all strings:
$array = array_map('strval', $array);
hakre
  • 193,403
  • 52
  • 435
  • 836