开发者

PHP how to access object dynamicly?

I've got the following object:

$json = '{"response": {"status": {"message": "Success"}, "images": [{"url": "http://domain.com/images/0001.jpg"}, {"url": "http://domain.com/images/0001.jpg"}]}}'; 
$obj  = json_decode($json);

Then i have an array:

$obj_path = array('response', 'images');

I can access 开发者_JAVA技巧images within $obj like so $obj->$obj_path[0]->$obj_path[1]

How would i do it more dynamically? Something along the line of...

$obj_path_count = count($obj_path);
for($i=0; $i<$obj_path_count; $i++)
{
   $obj_access_path .= '->' . $obj_path[$i]; //Build path to the access the object?
}
var_dump($obj . $obj_access_path); // Display object images

The above code gives the following error

Object of class stdClass could not be converted to string


You can't access a full path like that, the interpolation only goes one level deep. You can do something like this though:

$obj_access = $obj;
foreach($obj_path as $path_item)
{
   $obj_access = $obj_access->$path_item;
}
var_dump($obj_access); // Display object images

Looking at your JSON though, I don't think this will help fix whatever problem it is you are trying to solve however.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜