如何从字符串json中提取数组?

时间:2014-11-18 20:43:58

标签: php json

我有这个字符串:

$string =  '{"2r0ij":{"id":"2r0ij","title":"Official Reddit announcements","subscribers":7225390}}'

我希望转换为数组。我尝试使用json_decode($ string),但结果为null。与print_r($ string)相同的结果。

有什么问题?

2 个答案:

答案 0 :(得分:0)

您需要将json_decode()与'true'标志一起使用 -

$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

这是一个有效的example。该字符串减去开始和结束引号,在JSONLint验证。

答案 1 :(得分:0)

如果要将其转换为数组,则需要将json_decode()的第二个参数设置为true

$array = json_decode($string, true);
print_r($array);