1

I am getting a JSON response which looks like this:

stdClass Object
(
 [location00] => Array
 (
 [0] => stdClass Object
 (
 [id_0] => Array
 (
 [0] => stdClass Object
 (
 [id] => 1
 [name] => Wanted by Aryurumoka
 [gold_reward] => 58900
 [event] => 0
 [description] => Not provided.
 )
 )
 )
 )
)

For example, i am able to get [name] by $quests->location00[0]->id_0[0]->name.

Lets say i create a new variable $location = 'location00'. Now if i try $quests->$location[0]->id_0[0]->name', i am getting Undefined property: stdClass::$l error. I tried $location = 'location00[0]' as well however i have completly no idea why this happenes. How can i assign location00 to variable to use it while parsing JSON?

asked Mar 14, 2015 at 12:45

2 Answers 2

2

You can use associative array or $obj->{$var} :

<?php
$quests = json_decode($json, true);
$location = 'location00';
$name = $quests[$location][0]['id_0'][0]['name'];
answered Mar 14, 2015 at 12:53
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. Using data as array is really cool, however i am trying to start working with objects. +1 though
1

I'd try to get new JSON, but you can interpolate object property retrieval with braces:

$quests->{$location}[0]
answered Mar 14, 2015 at 12:51

4 Comments

Ahh, nice, this worked perfectly. Since i am quite new to parsing JSON, could you please explain or give link to manual that explains purpose of braces?
@lolbas this has nothing to do with JSON specifically ... it's just a PHP syntax thing.
@lolbas This is a PHP concept called variable variables
@lolbas actually you need the braces so that the variable interpolation is done first. If you do $quests->$location[0] it would be similar as if you did $quests->{$location[0]}

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.