致命错误:不能将字符串偏移用作数组 - 从JSON响应中解析字符串

时间:2012-03-28 19:55:21

标签: php json parsing

我正在使用api进行电影约会,我试图解析一个json数组。香港专业教育学院试图解析发布日期,但我收到此错误 - 致命错误:不能使用字符串偏移作为数组

以下是数组

的示例
Array
(
    [total] => 17
    [movies] => Array
        (
            [0] => Array
                (
                    [id] => 22494
                    [title] => Titanic (in 3D)
                    [year] => 1997
                    [mpaa_rating] => PG-13
                    [runtime] => 195
                    [critics_consensus] => A mostly unqualified triumph for Cameron, who offers a dizzying blend of spectacular visuals and old-fashioned melodrama.
                    [release_dates] => Array
                        (
                            [theater] => 2012-04-04
                            [dvd] => 1999-08-31
                        )

这是我收到错误的简单代码。

<?php
$url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=px8rr7zr5c6qjwpea66gdf93&page_limit=18';
$json = file_get_contents($url);
$data = json_decode($json, TRUE);

foreach($json['releasedates']['theatre'] as $item) {
    print $item['theatre'];
}

?>

理想情况下,我想将日期解析为变量,并能够将它们与当天进行比较

感谢您的帮助:)

1 个答案:

答案 0 :(得分:2)

您的foreach使用的是错误的变量(并且根据数据拼写剧院错误)

编辑: 你的脚本,工作:

<?php
    $url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?apikey=px8rr7zr5c6qjwpea66gdf93&page_limit=18';
    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);

    foreach($data['movies'] as $item) {
        echo $item['title'] . ' is opening on ' . $item['release_dates']['theater'] . "\n";
    }