我有这个字符串:
$string = '{"2r0ij":{"id":"2r0ij","title":"Official Reddit announcements","subscribers":7225390}}'
我想转换为数组。我尝试使用 json_decode($string),但结果为空。与 print_r($string) 的结果相同。
怎么了?
如果要将其转换为数组,则需要将 json_decode()
的第二个参数设置为 true
:
$array = json_decode($string, true);
print_r($array);
你确实需要使用带有"true"标志的json_decode()
-
$string = '{"2r0ij":{"id":"2r0ij","title":"Official Reddit announcements","subscribers":7225390}}';
$foo = json_decode($string, true);
print_r($foo);
echo $foo['2r0ij']['title'];
结果是:
Array ( [2r0ij] => Array ( [id] => 2r0ij [title] => Official Reddit announcements [subscribers] => 7225390 ) )
Official Reddit announcements
这是一个工作示例。字符串减去开始和结束引号,在 JSONLint 进行验证。