0

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 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

3
  • What exactly is the point of doing it dynamically, in your case? Do you want to access variables by a variable name ($$varName)? Do you want to create more concise code? Or make decisions on which array item to pick? Commented Jun 15, 2011 at 1:05
  • I've got number of objects and an array of the items i need to grab. Guess i am after more concise code which lets me pick the elements of the object that are defined in an array Commented Jun 15, 2011 at 1:11
  • By the way, the . in var_dump should be a comma, I believe, whence the error. Commented Jun 15, 2011 at 1:27

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.