PHP JSON decode - stdClass
Asked Answered
P

3

12

I was having a question about making a 2D JSON string

Now I would like to know why I can't access the following:

$json_str = '{"urls":["http://example.com/001.jpg","http://example.com/003.jpg","http://example.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str);
// echo print_r($j_string_decoded); // OK

// test get url from second item
echo j_string_decoded['urls'][1];
// Fatal error: Cannot use object of type stdClass as array
Primero answered 2/11, 2010 at 18:11 Comment(0)
R
27

You are accessing it with array-like syntax:

echo j_string_decoded['urls'][1];

Whereas object is returned.

Convert it to array by specifying second argument to true:

$j_string_decoded = json_decode($json_str, true);

Making it:

$json_str = '{"urls":["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';

$j_string_decoded = json_decode($json_str, true);
echo j_string_decoded['urls'][1];

Or Try this:

$j_string_decoded->urls[1]

Notice the -> operator used for objects.

Quoting from Docs:

Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

http://php.net/manual/en/function.json-decode.php

Reel answered 2/11, 2010 at 18:16 Comment(0)
T
7

json_decode by default turns JSON dictionaries into PHP objects, so you would access your value as $j_string_decoded->urls[1]

Or you could pass an additional argument as json_decode($json_str,true) to have it return associative arrays, which would then be compatible with $j_string_decoded['urls'][1]

Torgerson answered 2/11, 2010 at 18:16 Comment(0)
D
6

Use:

json_decode($jsonstring, true);

to return an array.

Dilatory answered 2/11, 2010 at 18:15 Comment(2)
Saved me! :vvvvvvFibrinolysis
This should be answer too, change 2nd parameters from default false to true will solve PHP fatal error > illegal convert stdClass Object to ArrayDonettedoney

© 2022 - 2024 — McMap. All rights reserved.