Basic
Basic

Reputation: 26766

Variable Variables in Multi-Level objects

I'm being handed some data which is not well defined and subject to change (or at least there's no formal spec and properties may be added/removed). I have no control over the data which I receive as JSON and then json_decode into an anonymous object.

In an attempt to make sense of the data, I'd like to build some mappings. Assuming the data defines a person, something like:

$Data = json_decode($TheRawData);

$Mappings->Personal['Firstname']="FirstName";
$Mappings->Personal['Employer']="Employment->CurrentEmployer";

Which, if I were doing it by hand would mean the firstname can be found at $Data->FirstName and the Current Employer is at $Data->Employer->CurrentEmployer

I'd like to store the info for the mappings in the database for maintainability. Unfortunately, when I attempt to parse the object for the defined properties as shown below:

foreach($Mappings->Personal as $Key=>$Value) {
    print $Key . ": " . $Data->{$Value};    
}

The firstname works perfectly (as expected) but it doesn't like the selector for the 2nd entry, presumably because it's spanning multiple objects and would require repeated lookups.

Can someone tell me if there's any way I can map to arbitrary locations in my object?

Upvotes: 0

Views: 483

Answers (1)

Gleeb
Gleeb

Reputation: 166

A quick Google turned up nothing useful, so I'd have to suggest something a little more iterative.

$Data = json_decode($TheRawData);

$Mappings->Personal['Firstname']=array("FirstName");
$Mappings->Personal['Employer']=array("Employment","CurrentEmployer");

foreach($Mappings->Personal as $Key=>$Value) {
    $Result = $Data;
    foreach($Value as $PropertyName) {
        $Result = $Result->$PropertyName;
    }
    print $Key . ": " . $Result;    
}

I've not tested this, but something along these lines should work for you.

Upvotes: 1

Related Questions