在php中解析复杂的json

时间:2015-08-20 05:27:31

标签: php json parsing

我试图使用json_decode和file_get_contents来获得股票价格。 我试图用关联数组获得价格,但我得到未定义的索引错误,坦率地说,我被卡住了。 我的代码:

  $jsondata =file_get_contents("http://finance.yahoo.com/webservice/v1/symbols/wmt/quote?format=json");
  $json = json_decode($jsondata, true);
  $list = $json['list'];
  $resource = $list['resources'];
  $resource = $resource['resource'];
  $fields = $resource['fields'];
  $price = $fields['price'];
  echo $price;

JSON:

{
    list : {
        meta : {
            type : "resource-list",
            start : 0,
            count : 1
        },
        resources : [{
                resource : {
                    classname : "Quote",
                    fields : {
                        name : "Wal-Mart Stores, Inc. Common St",
                        price : "68.570000",
                        symbol : "WMT",
                        ts : "1440014635",
                        type : "equity",
                        utctime : "2015-08-19T20:03:55+0000",
                        volume : "16333364"
                    }
                }
            }
        ]
    }
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

以下一行都出错:

$resource = $resource['resource'];

此时,$resource已经是一个非关联数组,你应该只是循环遍历:

$resources = $list['resources'];

foreach($resources as $resource) {
    $name = $resource['classname'];
    $fields = $resource['fields'];
    $price = $fields['price'];
}

答案 1 :(得分:0)

试试这个,它应该可行,

$json = json_decode($jsondata, true);
$resoureces=$json['list']['resources'];
foreach ($resoureces as $value) {
$price=$value['resource']['fields']['price'];
}
print_r($price);