0

I'm trying to get a value from stdClass Object array with no success.

Here is the code I'm running:

 $myjson =
 '{"2":{"label":"","value":"","type":null,"validation":null,"required":null},
 "6":{"label":"files","value":"getThisValue","type":"file0","validation":null,"required":null},
 "3":{"label":"location","value":"val3","type":"hidden","validation":"","required":"0"}
 ,"0":{"custom3":"zz","value":"","label":""},"1":{"custom3":"zz","value":"","label":""}
 }';

$json = json_decode($myjson);

echo $json[6]->'value';

This is doesn't work, If I Print_r the JSON after decoding (print_r($json)), the array will look like this:

stdClass Object ( 
    [2] => stdClass Object ( [label] => [value] =>
[type] => [validation] => [required] => ) 
    [6] => stdClass Object (
[label] => files [value] => getThisValue [type] => file0 [validation]
=> [required] => ) 
    [3] => stdClass Object ( [label] => location [value] => val3 [type] => hidden [validation] => [required] => 0 ) 
    [0]
=> stdClass Object ( [custom3] => zz [value] => [label] => ) 
    [1] => stdClass Object ( [custom3] => zz [value] => [label] => ) )

I need the Value: getThisValue. Any idea how I can get it? (I tried many options with no success).

4 Answers 4

3

Try echo $json["6"]["value"]; But for this you have to use json_decode($myjson, true); true, to get an array.

Because it's going to be two arrays inside each other and not an object you have to use 2 brackets.

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

2 Comments

Thanks.. thats the answer ;)
No Problem my friend.
1

You can't use a std object as an array. But in order to get your code working just add this line:

$json = get_object_vars($json);

After this you can access it like this:

echo $json[6]->value;

Comments

1

You could add true to your json_decode, like this: json_decode($myjson, true);, it will now convert your json object to an associative array.

And from there on you can get to the value you want by requesting the key, just like other arrays.

$newArray = json_decode($myjson, true);
echo $newArray['something'];

Comments

0

If you want to get the values from stdObject without converting it to array, you can do it like this:

echo $json->{'6'}->value

You can use the {'property_name'} notation to get a value of a class property with non-standard name (for ex. a number).

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.