0

I have an array like so:

array(
    'a'=>array(
        'a'=>3,
        'f'=>5,
        'sdf'=>0),
    't'=>array(
        'a'=>1,
        'f'=>2,
        'sdf'=>5),
    'pps'=>array(
        'a'=>1,
        'f'=>2,
        'sdf'=>3)
);

Notice how the sub-arrays are the same for each top-level array. If I wanted to, what's the easiest way to combine the sub-arrays so that I'm left with a one-dimensional array like:

array(
    'a'=>5,
    'f'=>9,
    'sdf'=>8
);

3 Answers 3

2

What about this?

$result = array();
foreach ($array as $key => $value) {
  foreach ($value as $k => $a) {
    if ( ! isset($result[$k])) $result[$k] = 0;
    $result[$k] += $a;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was using .= instead of += - saved me a headache!!
0

What about two nested foreach and actually creating a new array ?

$input = array(
    'a'=>array(
        'a'=>3,
        'f'=>5,
        'sdf'=>0),
    't'=>array(
        'a'=>1,
        'f'=>2,
        'sdf'=>5),
    'pps'=>array(
        'a'=>1,
        'f'=>2,
        'sdf'=>3)
);

$output = array();
foreach ($input as $v) {
    foreach ($v as $k2 => $v2) {
        if (!isset ($output[$k2])
            $output[$k2] = 0;
        $output[$k2] += $v2;
    }
}

/* Now $output = array(
       'a'=>5,
       'f'=>9,
       'sdf'=>8
   ); */

Comments

0
array_walk_recursive($array, function($val, $key) {
  global $result;
  $result[$key] += $val;
});

Comments

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.