PHP: How to access json object chain with hyphenated names -
PHP: How to access json object chain with hyphenated names -
referring question ...
how access object property hyphenated name?
... have additional one:
i want access json property saved in variable ... ...
$var = '$obj->my-prop';
if
$var = 'my-prop'
... solve problem hyphenated name calling via
$obj->{$var}
which lead
$obj->{'my-prop'}
... said in preceding question.
but: variable contains preceding object value ('$obj'). calling via {$var} leads {'$obj->my-prop'}, invalid, way solve seams to explode('->',$var) , concatenate it, mess.
does know 'solution idéale'? :-)
edit: solution idéale of 1 has solve question whether maintain literal object syntax saving variable string looks(!) object. hence unpackpath function of h2ooooooo proper one. in contrast save variable in chain array (as tobe said) open more scheme appropriate way of processing data. json_decode string 'a->b' not possible though.
you have create own parser (using eg. explode()
mentioned).
<?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) { homecoming $value; } else { homecoming unpackpath($value, array_slice($path, 1)); } }
usage: $foo = new foo(); var_dump( unpackpath($foo, 'bar->oof->id') ); // int(123)
demo.
please note have define start object ($foo
) in order not utilize global variables.
php json object chain hyphen
Comments
Post a Comment