douxing2652 2012-03-28 10:29
浏览 14
已采纳

多级对象中的变量变量

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?

  • 写回答

1条回答 默认 最新

  • dongzhang3482 2012-03-28 10:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?