0

In the multidimensional array like the example given below, how to calculate values with the same index and store them in a new array:

$a = array(
    0 => array(
        "a" =>  12,
        "b" =>  78,
        "c" =>  5,
        "d" =>  5,
    ),
    1 => array(
        "a" =>  5,
        "b" =>  12,
        "c" =>  7,
        "d" =>  16,
    ),
    2 => array(
        "a" =>  13,
        "b" =>  79,
        "c" =>  12,
        "d" =>  16,
    ),
    3 => array(
        "a" =>  4,
        "b" =>  1,
        "c" =>  6,
        "d" =>  4,
    )
);

We should get an array like this:

$sum = array (
    "a"   =>  35,
    "b"   =>  170,
    "c"   =>  30,
    "d"   =>  41,
);

Or like this:

$sum = array (
    0   =>  35,
    1   =>  170,
    2   =>  30,
    3   =>  41,
);
Tpojka
  • 6,996
  • 2
  • 29
  • 39
Hedayatullah Sarwary
  • 2,664
  • 3
  • 24
  • 38

1 Answers1

2

Try the following example:

$sum = [];

foreach($a as $item) {
    foreach($item as $key => $value) {
        if (!isset($sum[$key])) $sum[$key] = 0;
        $sum[$key] += $value;
    }
}

print_r($sum);

If all items have the same keys:

$sum = array_fill_keys(array_keys(reset($a)), 0);

foreach($sum as $key => &$value) {
    $value = array_sum(array_column($a, $key));
}

print_r($sum);
id'7238
  • 2,428
  • 1
  • 3
  • 11