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]
$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.
精彩评论