<?php
function merge(array ...$sets)
{
/**
* group contributions by name
*/
$contributions = array_reduce(
$sets,
function (array $contributions, array $set) {
foreach ($set as $element) {
$name = $element['P_Name'];
$contribution = $element['Contribution'];
if (!array_key_exists($name, $contributions)) {
$contributions[$name] = [];
}
$contributions[$name][] = $contribution;
}
return $contributions;
},
[]
);
/**
* normalize the array so we remove the name as key, and return a tuple of name and contribution, with the desired
* structure
*/
return array_values(array_map(function (array $contribution, $name) {
return [
'Contribution' => array_sum($contribution),
'P_Name' => $name,
];
}, $contributions, array_keys($contributions)));
}
$a = [
[
'Contribution' => 1000,
'P_Name' => 'A',
],
[
'Contribution' => 1500,
'P_Name' => 'B',
],
];
$b = [
[
'Contribution' => 100,
'P_Name' => 'A',
],
[
'Contribution' => 200,
'P_Name' => 'B',
],
];
$merged = merge($a, $b);
var_dump($merged);
preferences:
54.46 ms | 402 KiB | 5 Q