So I have this associative array (dump done with kint)
d
Instead of having the key "Conference
" repeating 3 times. I want to have it just once and sum the 3 values into one in order to have something like:
Conference : 4534
And same thing for all other keys that are repeating..
Is there a native function that can do that ?
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
Normally add a new element in an existing associative array it will get appended at the end of that array. print_r( $arr ); ?> So, a new element can not be added directly at the beginning of an associative array but the existing array can be appended at the end of a new array where the first element is the new element.
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
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With