开发者

Type Casting an Decoded Json Object to array, generate error while accessing it

I decoded a json string and then Type casted it into any Array and tried to access it later. But it generate Undefined Index Error

H开发者_运维知识库ere is my sample code

$json = '{"1":"Active","0":"Inactive"}'; //Yes, it is a valid Json String
$decodedObject = json_decode($json);
$array = (array)$decodedObject;
echo $array['1']; // This generates undefinded Index 1 Error

Here is the display of the array and object

stdClass Object
(
    [1] => Active
    [0] => Inactive
)

Array
(
    [1] => Active
    [0] => Inactive
)


1.) instead of making it in two steps how about doing it like:

$decodedArray = json_decode($json, true);

it will directly give you the array instead of object

2.) make sure your json code is corret:

{"1":"Active","0":"Inactive"}

3.) your var_dump shows that array{[1]=>.... so why refering it like $array['1'] can it be even simpler $array[1]


No, it is not a valid JSON string (JSONLint is your friend). You used a comma instead of a colon:

{"1":"Active","0","Inactive"} // invalid
{"1":"Active","0":"Inactive"} // valid
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜