I have a multidimensional array in the following format :
array (
0 =>
array (
'manual' => 1,
'cancelled' => 1,
'expired' => 1,
'earned' => 1,
'user' =>
array (
'user1' => 1,
'user2' => 1,
'user3' => 1,
'user4' => 1,
),
'transfer' =>
array (
'transfer1' =>
array (
'key1' => 1,
'key2' => 1,
'key3' => 1,
),
'transfer2' =>
array (
'key5' => 1,
'key6' => 1,
'key7' => 1,
),
),
'date' => '2018-03-07',
),
1 =>
array (
'manual' => 1,
'cancelled' => 1,
'expired' => 1,
'earned' => 1,
'user' =>
array (
'user1' => 1,
'user2' => 1,
'user3' => 1,
'user4' => 1,
),
'transfer' =>
array (
'transfer1' =>
array (
'key1' => 1,
'key2' => 1,
'key3' => 1,
),
'transfer2' =>
array (
'key5' => 1,
'key6' => 1,
'key7' => 1,
),
),
'date' => '2018-03-08',
),
)I need to calculate the sum of the array values with same index. So the total array should be as the following
Array
(
[total] => Array
(
[manual] => 2
[cancelled] => 2
[expired] => 2
[earned] => 2
[user] => Array
(
[user1] => 2
[user2] => 2
[user3] => 2
[user4] => 2
)
[transfer] => Array
(
[transfer1] => Array
(
[key1] => 2
[key2] => 2
[key3] => 2
)
[transfer2] => Array
(
[key5] => 2
[key6] => 2
[key7] => 2
)
)
That is the total should have the same format except date, but it needs to show the total sum of the value. How can this be done in PHP ? I have used the following code
$final = array_shift($input);
foreach ($final as $key => &$value){
$value += array_sum(array_column($input, $key));
}
unset($value);
var_dump($final);
where $input is considered as the first array and $final is total. I think this only work with single indexes.
same index.-> whcih same index you used to compare ?manualin the 0th element needs to be added tomanualin the first element. So in total the value formanualindex is 2. This is same for all other indexes.$total['total']['manual'] = $array[0]['manual']+ $array[1]['manual']and$total['total']['cancelled'] = $array[0]['cancelled']+ $array[1]['cancelled']and$total['total']['user']['user1'] = $array[0]['user']['user1']+ $array[1]['user']['user1']