Eran Levi
Eran Levi

Reputation: 363

Get stdClass Object value

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

Upvotes: 0

Views: 3161

Answers (4)

Alexander Grasberger
Alexander Grasberger

Reputation: 356

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.

Upvotes: 3

winglot
winglot

Reputation: 21

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

Upvotes: 0

user1897253
user1897253

Reputation:

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'];

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

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;

Upvotes: 1

Related Questions