$response = '{"items":
[{"id":"1","food":"rice","Amount":"100","condition":"paid"},\
{"id":"2","food":"beans","Amount":"200","condition":"paid"},\
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},\
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},\
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
echo $response['items'][1]['food'];
Error: "Illegal string offset 'items'
Why can't I access the data?
You must decode a json string before using it as an object/array.
Your question shows you want to use it as an array, that means the second parameter of json_decode should be true.
However the \
makes your string invalid. Is that copy paste error or is that the actual string?
If it is the actual string then you may need to remove the \
before decoding.
I assume it's a copy paste error?
$response = '{"items":
[{"id":"1","food":"rice","Amount":"100","condition":"paid"},
{"id":"2","food":"beans","Amount":"200","condition":"paid"},
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
$arr = json_decode($response, true);
echo $arr['items'][1]['food']; // beans
If you need to remove the unwanted \
you can use stripslashes.
$arr = json_decode(stripslashes($response), true);
To replicate the error you get you need to do the following:
$response = '{"items":
[{"id":"1","food":"rice","Amount":"100","condition":"paid"},\
{"id":"2","food":"beans","Amount":"200","condition":"paid"},\
{"id":"3","food":"yam","Amount":"50","condition":"not paid"},\
{"id":"4","food":"tomatoes","Amount":"100","condition":"paid"},\
{"id":"5","food":"potato","Amount":"700","condition":"paid"}]}';
$arr = (string)json_decode($response, true); // json_decode returns NULL and the string cast makes it "NULL"
echo $arr['items'][1]['food']; // Warning: Illegal string offset 'items'
// or
echo $response['items'][1]['food']; // Warning: Illegal string offset 'items'
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments