Just set all properties of all objects in $arr1
to a copy of $arr2
which is the merge array arr_merged
then:
$arr_merged = $arr2;
foreach ($arr1 as $key => $obj)
{
foreach ($obj as $property => $value)
{
$arr_merged[$key]->$property = $value;
}
}
Works with all visible properties (normally those are public for the objects in your question). Depending which objects should supersede what, you might want to swap $arr1
with $arr2
. In this example, object properties in $arr1
would overwrite same-named properties in $arr2
.
Unlike array_replace_recursive
no similar function exists in PHP for stdClass type of objects. You could convert both arrays of objects to arrays of arrays and then use that function however:
# convert objects to arrays
foreach(array('arr1', 'arr2') as $var)
$$var = array_map('get_object_vars', $$var);
$arr_merged = array_replace_recursive($arr1, $arr2);
# convert arrays to objects
array_walk($arr_merged, function(&$v) {$v = (object) $v;});
As-is this does not look more useful to me as it's not as clear as the foreach. Probably if you more often need the functionality you can think about wrapping it into a function with a nice name.
Related: What is the best method to merge two PHP objects?