Home > database >  SUM associative Array index dynamically on PHP
SUM associative Array index dynamically on PHP

Time:01-13

I have a result PHP array like this

$listResult = array(
0 => array(
    0 => 1,
    1 => 15,
    2 => 4,
    3 => 52
),
1 => array(
    0 => 2,
    1 => 0,
    2 => 3,
    3 => 2
),
2 => array(
    0 => 3,
    1 => 5,
    2 => 9,
    3 => 1
),
3 => array(
    0 => 4,
    1 => 10,
    2 => 2,
    3 => 5
),
4 => array(
    0 => 1,
    1 => 1,
    2 => 2,
    3 => 3
));

How to sum each keys? The result should be like this:

$sumResult = array(
    0 => 11,
    1 => 31,
    2 => 20,
    3 => 63
);

Already search in stackoverflow but the answer required key, in this case I just want to sum each index dynamically without a key. Sorry if my english is bad.

CodePudding user response:

Use array_column() to get an array of all the elements with the same key, and array_sum() to sum them.

$sumResult = [];
foreach (array_keys($listResult[0]) as $key) {
    $sumResult[$key] = array_sum(array_column($listResult, $key));
}
  •  Tags:  
  • Related