duandushang5148 2014-10-17 09:21
浏览 57
已采纳

PHP:如何使用带连字符的名称访问json对象链

Referring to this question ...

How do I access this object property with a hyphenated name?

... I have an additional one:

I want to access a json property that is saved in a variable ... something like ...

$var = '$obj->my-prop';

IF it would just be

$var = 'my-prop'

... I could solve the problem with the hyphenated name by calling it via

$obj->{$var}

which would lead to

$obj->{'my-prop'}

... like it is said in the preceding question.

BUT: My variable also contains the preceding object value ('$obj'). As calling it via {$var} leads to {'$obj->my-prop'}, which is invalid, the only way to solve it seams to be to explode('->',$var) and then concatenate it, which is a mess.

Does someone know the 'solution idéale'? :-)


EDIT: so the solution idéale of one has to solve the question whether to keep this literal object syntax by saving the variable as string that just looks(!) like an object. therefore the unpackPath function of h2ooooooo would be a proper one. In contrast to that to save that variable in a chain as array (as ToBe said) would open a more system appropriate way of processing data. To json_decode a string like 'a->b' is not possible though.

  • 写回答

1条回答 默认 最新

  • dtftao7249656 2014-10-17 09:30
    关注

    You have to make your own parser (using eg. explode() like you mentioned).

    Setup:

    <?php
    
    class Foo {
        public $bar;
    
        public function __construct() {
            $this->bar = new Bar();
        }
    }
    
    class Bar {
        public $oof;
    
        public function __construct() {
            $this->oof = new Oof();
        }
    }
    
    class Oof {
        public $id = 123;
    }
    
    function unpackPath($object, $path) {
        if (is_string($path)) {
            $path = explode('->', $path);
        }
    
        $value = $object->{$path[0]};
    
        if (count($path) == 1) {
            return $value;
        } else {
            return unpackPath($value, array_slice($path, 1));
        }
    }
    

    Usage:

    $foo = new Foo();
    var_dump( unpackPath($foo, 'bar->oof->id') ); // int(123)
    

    DEMO.

    Please note that you have to define your start object ($foo) in order to not use global variables.

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等