2

$arr1 is an associative array of anonymus objects:

array
  15898 => 
    object(stdClass)[8]
      public 'date' => int

$arr2 is another associative array with two (or more, it's not fixed) properties:

array
  15898 => 
    object(stdClass)[10]
      public 'fruits'
      public 'drinks'

I can't find any function for intersect and content fusion when dealing with objects. Basically i'd like to obtain:

array
  15898 => 
    object(stdClass)[8]
      public 'date' => int
      public 'fruits'
      public 'drinks'

Question is: is this even possible?

hakre
  • 193,403
  • 52
  • 435
  • 836
gremo
  • 47,186
  • 75
  • 257
  • 421

2 Answers2

1

If I understand you correctly :-

$key = 15898;
$a[$key] = (object) array('date'=>time());
$b[$key] = (object) array('date2'=>time());
$c[$key] = (object) array_merge(get_object_vars($a[$key]), 
                                get_object_vars($b[$key]));

var_dump($c);

The above is make use on get_object_vars to extract all the properties belong to object $a, $b,
and merge it to a new array, then do a casting to object

With this, you are able to assign all properties (public) from object $a, $b to $c

ajreal
  • 46,720
  • 11
  • 89
  • 119
0

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?

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836