doxrxwn2252 2014-06-13 17:19
浏览 47
已采纳

如何通过解码的JSON类中的反射访问数字属性?

Here is the object I decode from JSON in PHP:

php > var_dump($v);
object(stdClass)#9 (1) {
  ["objects"]=>
  object(stdClass)#10 (2) {
    ["16"]=>
    object(stdClass)#14 (2) {
      ["id"]=>
      int(16)
      ["name"]=>
      string(8) "Object 1"
    }
    ["32"]=>
    object(stdClass)#11 (2) {
      ["id"]=>
      int(20)
      ["name"]=>
      string(8) "Object 2"
    }
  }
}
php > $rc = new \ReflectionClass($v);
php > var_dump($rc);
object(ReflectionClass)#17 (1) {
  ["name"]=>
  string(8) "stdClass"
}
php > var_dump($rc->getProperties());
array(0) {
}

As you can see, ReflectionClass fails to detect any of the properties. I cannot do $v->objects->32, because PHP does not allow numeric properties. I also cannot decode to an associative array, because that would break JSON handling in other parts of my system.

  • 写回答

1条回答 默认 最新

  • douweilei2307 2014-06-13 17:24
    关注

    The simpliest way is to use the second parameter of json_decode and set it to true. Using this method, you can access the vars like in any other associative array

    $v = json_decode($data, true);
    $value = $v['objects']['32']
    

    if you cant change the json_decode call, you can use the following syntax to access the var

    $v = json_decode('{"objects":{"16":{"id":16,"name":"Object 1"},"32":{"id":20,"name":"Object 2"}}}');
    var_dump($v->objects->{'16'});
    

    and even

    $name = '16';
    var_dump($v->objects->{$name});
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用