这是我的代码:
echo '<br/>';
echo 'Json data from DB '.json_encode($output);
$data=array();
$array=json_decode($output,true);
echo '<br/>';
echo 'Concerted into an array '.json_encode($array);
这是输出:
Json data from DB [{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]
Concerted into an array null
为什么json_devode返回null?如果我这样尝试:
$data = '[{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]';
// convert to an array
$data = json_decode($data, true);
然后正常打印出来:
Json data from DB [{"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","3":"1","key-4":"1"}]
Concerted into an array {"0":"1","key-1":"1","1":"1","key-2":"1","2":"1","key-3":"1","4":"1","key-4":"1"}
答案 0 :(得分:4)
因为json_decode
采用字符串而$output
不是字符串(由json_encode
证明:它是一个数组)。
答案 1 :(得分:1)
你好像在混淆。在您的示例中$output
似乎已经是一个数组,您想再次解码它?怎么样?
执行此操作时:
json_encode($output);
它返回一个正确的JSON对象,这意味着$output
已经是一个数组。你不能json_decode
非JSON对象。您似乎可以直接使用$output
,或者需要更清楚地说明您的问题。