Monday 3 September 2018

How to merge tables with the same key and a different value in PHP?

I have arrays similarly to these:

0 => Array ( [0] => Finance / Shopping / Food, [1] => 47 )
1 => Array ( [0] => Finance / Shopping / Food, [1] => 25 )
2 => Array ( [0] => Finance / Shopping / Electronic, [1] => 190 )

I need to create one array with [0] as a key and [1] as value.
The tricky part is that if the [0] is same it add [1] to existing value.
So the result I want is:
array ([Finance / Shopping / Food]=> 72, [Finance / Shopping / Electronic] => 190);

thanks

// array array_merge_values($base[, $merge[, ...]])
// Combines multiple array values based on key
//   (adding them together instead of the native array_merge using append)
//
// $base       - array to start off with
// $merge[...] - additional array(s) to include (and add their values) on to the base
function array_merge_values()
{
  $args = func_get_args();

  $result = $args[0];
  for ($_ = 1; $_ < count($args); $_++)
    foreach ($args[$_] as $key => $value)
    {
      if (array_key_exists($key,$result))
        $result[$key] += $value;
      else
        $result[$key] = $value;
    }
  return $result;
}

$array1 = Array('foo' => 5, 'bar' => 10, 'foobar' => 15);
$array2 = Array('foo' => 20,                             'foohbah' => 25);
$array3 = Array(            'bar' => 30);
var_dump(array_merge_values($array1,$array2,$array3));

Result:
array(4) {
  ["foo"]=>
  int(25)
  ["bar"]=>
  int(40)
  ["foobar"]=>
  int(15)
  ["foohbah"]=>
  int(25)
}

0 comments:

Post a Comment