Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative array, sum values of the same key

So I have this associative array (dump done with kint)

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 ?

like image 318
Alucard Avatar asked Jan 07 '13 12:01

Alucard


People also ask

Can associative array have same key?

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.

How do you add values in an associative array?

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.


1 Answers

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
        )

)
like image 103
Baba Avatar answered Nov 14 '22 13:11

Baba