1

The input array:

[
    [1 => 2],
    [1 => 2],
    [2 => 1],
    [3 => 1],
]

I want this output:

[
    [1 => 4],
    [2 => 1],
    [3 => 1],
]
4
  • Is there always only one element inside each sub array? Commented Mar 26, 2014 at 7:57
  • I want [0] => Array ( [1] => 2 ) [1] => Array ( [1] => 2 ) as [0] => Array ( [1] => 4 ) Commented Mar 26, 2014 at 7:57
  • 3
    Why does your result have a separate sub-array for each key? Why not a single associative array with all the results? Commented Mar 26, 2014 at 7:58
  • 2
    Happy you are really making us Sad. Commented Mar 26, 2014 at 7:59

3 Answers 3

2

Seems like a good case for array_reduce():

$res = array_chunk(array_reduce($arr, function(&$current, $item) {
    foreach ($item as $key => $value) {
        if (!isset($current[$key])) {
            $current[$key] = 0;
        }
        $current[$key] += $value;
    }
    return $current;
}, []), 1, true);

For the final result I'm using array_chunk(); it takes an array and creates single element sub arrays of each element.

Sign up to request clarification or add additional context in comments.

Comments

1
$result = array();
foreach ($input as $subarray) {
    foreach ($subarray as $key => $value) {
        if (isset($result[$key])) {
            $result[$key][$key] += $value;
        } else {
            $result[$key] = array($key => $value);
        }
    }
}
$result = array_values($result); // Convert from associative array to indexed array

Comments

0

By identifying unique groups and only pushing references into the result array, you can avoid needing to reindex the result after the loop. Demo

$result = [];
foreach ($array as $row) {
    $k = key($row);
    if (!isset($ref[$k])) {
        $ref[$k] = 0;
        $result[][$k] =& $ref[$k];
    }
    $ref[$k] += $row[$k];
}
var_export($result);

Output:

array (
  0 => 
  array (
    1 => 4,
  ),
  1 => 
  array (
    2 => 1,
  ),
  2 => 
  array (
    3 => 1,
  ),
)

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.