tftd
tftd

Reputation: 17062

How to merge objects in php?

I'm currently re-writing a class which handles xml files. Depending on the xml file and it's structure I sometimes need to merge objects.

Lets say once I have this:

<page name="a title"/>

And another time I have this:

<page name="a title">
  <permission>administrator</permission>
</page>

Before, I needed only the attributes from the "page" element. That's why a lot of my code expects an object containing only the attributes ($loadedXml->attributes()).
Now there are xml files in which the

<permission> 

element is required.
I did manage to merge the objects (though not as I wanted) but I can't get to access one of them (most probably it's something I'm missing).

To merge my objects I used this code:

(object) array_merge(
                     (array) $loadedXml->attributes(), 
                     (array) $loadedXml->children()
                    );


This is what I get from print_r():

stdClass Object ( 
    [@attributes] => Array ( [name] => a title ) 
    [permission]  => Array ( [0] => administrator ) 
) 


So now my question is how to access the @attributes method and how to move the arrays from [@attributes] to the main object?

Upvotes: 1

Views: 545

Answers (1)

ajreal
ajreal

Reputation: 47321

one of possible ways

$attr = '@attributes';
var_dump($obj->$attr);

To move the @attribute into property

foreach ($obj->$attr as $key=>$val)
{
  $obj->$key = $val;
}
unset($obj->$attr);

Upvotes: 1

Related Questions