Associative Array, Sum Values of the Same Key

Associative array, sum values of the same key

You can try

$data = array(
0 => array(
'event' => 'Conference',
'budget' => 3700,
),
1 => array(
'event' => 'Conference',
'budget' => 500,
),
2 => array(
'event' => 'Showroom',
'budget' => 1000,
),
3 => array(
'event' => 'Mission Chez client',
'budget' => 2000,
),
4 => array(
'event' => 'Séminaire',
'budget' => 700,
),
5 => array(
'event' => 'Livraison',
'budget' => 4000,
),
6 => array(
'event' => 'Conference',
'budget' => 334,
),
);

$sum = array_reduce($data, function ($a, $b) {
isset($a[$b['event']]) ? $a[$b['event']]['budget'] += $b['budget'] : $a[$b['event']] = $b;
return $a;
});


print_r(array_values($sum));

Output

Array
(
[0] => Array
(
[event] => Conference
[budget] => 4534
)

[1] => Array
(
[event] => Showroom
[budget] => 1000
)

[2] => Array
(
[event] => Mission Chez client
[budget] => 2000
)

[3] => Array
(
[event] => Séminaire
[budget] => 700
)

[4] => Array
(
[event] => Livraison
[budget] => 4000
)

)

how to get sum of associative array with same key using php

$val is a number not an array so get rid of the array_sum and just use the $val:

$arr = array();

foreach ($search as $srch_val => $srch_row) {
foreach ($srch_row as $key => $val) {
if(array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key] + ($val);
} else {
$arr[$key] = ($val);
}
}
}

Working Example.

How to sum values from associative array if there is the same key in php laravel

I used Collection and end up with the correct results. This could be achieve in a number of ways:

APPROACH 1:

collect($array)
->groupBy(function ($item) {
return collect($item)->keys()->first();
})
->map(function ($items) {
return collect($items)->flatten()->sum();
});

APPROACH 2:

collect($array)
->groupBy(function ($item) {
return array_key_first($item);
})
->map(function ($items) {
return collect($items)->flatten()->sum();
});

APPROACH 3:

$default = [
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => 0,
12 => 0,
];

collect($array)
->reduce(function ($carry, $item) {
$month = array_key_first($item);

$carry[$month] += $item[$month];

return $carry;
}, $default);

How to sum values of same key in array associative

What you want is impossible. Arrays cannot have duplicate keys:

php > $arr = array(1=>2, 1=>500);
php > var_dump($arr);
array(1) {
[1]=>
int(500) // hey! where'd "2" go?
}

If you want to store multiple values in a single key, then that key has to point to an array:

$arr = array();
$arr[1] = array(1, 500);
var_dump($arr);
php > var_dump($arr);
array(1) {
[1]=>
array(2) {
[0]=>
int(1)
[1]=>
int(500)
}
}

Associative Array SUM by key value php

This is one way to do it breaking it down into steps...

1.Create the Array that sums the matching delivery_plans

2.Rebuild the Array as required

<?php
$sum_array = [];
foreach($array as $item) {
if (key_exists($item['delivery_plan'], $sum_array)) {
$sum_array[$item['delivery_plan']] += $item['additional_amount_usd'];
} else {
$sum_array[$item['delivery_plan']] = $item['additional_amount_usd'];
}
}

$final_array = [];
foreach($sum_array as $key => $value) {
$final_array[] = ['delivery_plan' => $key, 'additional_amount_usd' => $value];
}

Refactoring the above so the code is not dependant upon hardcoded index names...

$key_name = 'delivery_plan';
$value_name = 'additional_amount_usd';

$sum_array = [];
foreach($array as $item) {
if (key_exists($item[$key_name], $sum_array)) {
$sum_array[$item[$key_name]] += $item[$value_name];
} else {
$sum_array[$item[$key_name]] = $item[$value_name];
}
}

$final_array = [];
foreach($sum_array as $key => $value) {
$final_array[] = [$key_name => $key, $value_name => $value];
}

And you could then turn that into a function if you so desired...

The result is (using var_dump())

array(2) {
[0]=>
array(2) {
["delivery_plan"]=>
string(13) "80::2020 / 07"
["additional_amount_usd"]=>
float(65.76)
}
[1]=>
array(2) {
["delivery_plan"]=>
string(13) "80::2020 / 09"
["additional_amount_usd"]=>
float(16.44)
}
}

Update:
Also Take a look at the solution provided by Kevin.
3v4l.org/h9Q5L

Sum 2 or more associative arrays values based on keys

Merge all arrays and sum values if it's an array

$res = array_merge_recursive($a, $b, $c,$d);
foreach($res as &$x) {
if (is_array($x)) {
$x = array_sum($x);
}
}
print_r($res);

demo

PHP array - Sum value of the same key when key are number

This should work for you:

Basically I just loop through your array and check if there is already an element in $result with the key of the first element of $v. If not I initialize it with an array_pad()'ed array of 0's + the current array of the iteration of the foreach loop.

And after this I loop through each element of $v expect the first one and add it to the result array.

At the end I just reindex the result array with array_values().

<?php

foreach($arr as $v){

if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);

$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];


}

$result = array_values($result);
print_r($result);

?>

output:

Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)

[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)

[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)

)

Associative array, values of the same key: get sums & averages of sibling values

Try

 $sum = array_reduce($data, function ($a, $b) {
if (!isset($a[$b['event']])) {
$a[$b['event']] = $b;
} else {
$a[$b['event']]['budget'] += $b['budget'];
$a[$b['event']]['people'] += $b['people'];
$a[$b['event']]['rate'] += $b['rate'];
}
return $a; });

For averages you could try:

 $sum = array_reduce($data, function ($a, $b) {
if (!isset($a[$b['event']])) {
$a[$b['event']] = $b;
$a[$b['event']]['rate_count'] = 1;
$a[$b['event']]['average_rate'] = array($b['rate']);
} else {
$a[$b['event']]['budget'] += $b['budget'];
$a[$b['event']]['people'] += $b['people'];
$a[$b['event']]['rate'] += $b['rate'];
$a[$b['event']]['rate_count'] += 1;
$a[$b['event']]['average_rate'] = $a[$b['event']]['rate'] / $a[$b['event']]['rate_count'];
}
return $a; });

php array sum key where value is same

The problem is you are adding a value even if it is not defined.

You can check if not set by and init the value to 0

if ( !isset($newarray[$n_k]) ) $newarray[$n_k] = 0;

Here is the complete code:

$array =  array( array('x1'=> 1, 'x2' => 3, 'y5' => 9), array('x1'=> 3, 'x4' => 1, 'y5' => 1), array('x1'=> 1, 'x8' => 5, 'a5' => 2), array('x1'=> 2, 'x10' => 3, 'b5' => 5));
$newarray = array();

foreach($array as $key => $values){
foreach($values as $n_k => $n_v) {
if ( !isset($newarray[$n_k]) ) $newarray[$n_k] = 0;
$newarray[$n_k] += $n_v;
}
}

This will result to:

Array
(
[x1] => 7
[x2] => 3
[y5] => 10
[x4] => 1
[x8] => 5
[a5] => 2
[x10] => 3
[b5] => 5
)


Related Topics



Leave a reply



Submit