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
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
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]
Use:
json_decode($jsonstring, true);
to return an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With