Associative array, sum values of the same key

Solution 1:

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
        )

)

Solution 2:

A simple suggestion:

$results = array();
foreach ($budgetByEventTemp as $value)
{
  if( ! isset($results[$value['event']]) )
  {
     $results[$value['event']] = 0;
  }

  $results[$value['event']] += $value['budget'];

}

var_dump($results);

Update according to comments

You can run over them again:

foreach($results as $key => $value)
{
  $structured_results[] = array('event' => $key, 'budget' => $value);
}

var_dump($structured_results);

Solution 3:

$sumArray = array();

foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
  $sumArray[$id]+=$value;
  }
}

print_r($sumArray);