-1

这是我的代码:

   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"}
4

2 回答 2

4

因为json_decode需要一个字符串而$output不是字符串(如json_encode: 它是一个数组所证明的那样)。

于 2012-12-15T12:07:30.327 回答
1

你好像把事情搞混了。在您的示例$output中似乎已经是一个数组并且您想再次对其进行解码?如何?

当你这样做时:

json_encode($output);

它返回一个正确的 JSON 对象,这意味着它$output已经是一个数组。而且您不能json_decode使用非 JSON 对象。看来你可以直接使用$output,或者你需要更清楚地说明你的问题。

于 2012-12-15T12:10:40.473 回答