-1

How can I merge two objects and sum the values of matching properties? I am hoping for a built in function in PHP, otherwise I am seeking an easy way of doing it.

See code under, where I have $objectA and $objectB which I want to become $obj_merged.

$objectA = (object) [];
$objectA->a = 1;
$objectA->b = 1;
$objectA->d = 1;
  
$objectB = (object) [];
$objectB->a = 2;
$objectB->b = 2;
$objectB->d = 2;
  
$obj_merged = (object) [
    'a' => 3,
    'b' => 3,
    'd' => 3
];
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Niklas
  • 357
  • 6
  • 20
  • Does this answer your question? [What is the best method to merge two PHP objects?](https://stackoverflow.com/questions/455700/what-is-the-best-method-to-merge-two-php-objects) – Tangentially Perpendicular Apr 04 '21 at 10:26
  • 4
    This is not really a "merge", more like a sum. What have you tried? Are the properties set in stone, or can they change? You can just loop over the object properties like you would an array's keys, if needed. This is pretty basic. – Jeto Apr 04 '21 at 10:26

2 Answers2

2

What you want to achieve is a sum of the properties. A merge would overwrite the values. There is no built-in PHP function to do this with objects.

But you can use a simple helper function where you could put in as many objects as you like to sum up the public properties.

function sumObjects(...$objects): object
{
    $result = [];
    foreach($objects as $object) {
        foreach (get_object_vars($object) as $key => $value) {
            isset($result[$key]) ? $result[$key] += $value : $result[$key] = $value;
        }
    }
    return (object)$result;
}

$sumObject = sumObjects($objectA, $objectB);
stdClass Object
(
    [a] => 3
    [b] => 3
    [d] => 3
)
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
1

There is no need to loop over both objects. Save the first object to the result object, then loop over the second object and add the related values between the current property and the result object. The null coalescing operator is used to add zero when there is no corresponding property in the result object.

Code: (Demo)

$result = $objectA;
foreach ($objectB as $prop => $value) {
    $result->$prop = ($result->$prop ?? 0) + $value;
}
var_export($result);

If the properties between the two objects are guaranteed to be identical, then there is no need to coalesce with zero. Demo

$result = $objectA;
foreach ($objectB as $prop => $value) {
    $result->$prop += $value;
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136