0

我是 php 新手,我很难从我的 JSON 对象中获取正确的数据。我不想从此JSON 链接获取 series_id、名称、单位和更新

这是示例 JSON:

{
   "request":{
      "category_id":40445,
      "command":"category"
   },
   "category":{
      "category_id":"40445",
      "parent_category_id":"40920",
      "name":"Btu",
      "notes":"",
      "childcategories":[

      ],
      "childseries":[
         {
            "series_id":"SEDS.PATCB.RI.A",
            "name":"All petroleum products total consumption, Rhode Island",
            "f":"A",
            "units":"Billion Btu",
            "updated":"22-APR-13 12.40.53 PM"
         },
         {
            "series_id":"SEDS.PATCB.TN.A",
            "name":"All petroleum products total consumption, Tennessee",
            "f":"A",
            "units":"Billion Btu",
            "updated":"22-APR-13 12.40.53 PM"
         }
      ]
   }
}

到目前为止,这是我的尝试:

<?php

 $API_url ='http://api.eia.gov/category/?api_key=FA92066C073D681DD8795C40F72E3B4B&category_id=40445';

 $string .= file_get_contents($API_url);// get json content
 $json_result = json_decode($string, true);//json decoder

 foreach ($json_result as $value) {

    foreach ($value as $key => $entry) {

        print_r($entry);

    }

 }

?>

我将如何从数组中获取所有 series_id、名称、单位和更新?

4

2 回答 2

2

只需使用这个:

foreach($json_result['category']['childseries'] as $value) {
     echo $value["series_id"], $value["name"], $value["units"], $value["updated"]; 
}

如果您查看 json 结构,您会发现它childseriescategory. 因此,$json_result['category']['childseries']是访问您想要的数组的方式。只需遍历它即可获得所需的数据。

于 2013-06-08T15:16:24.740 回答
0

我认为您可以使用范围直接访问所需的数组$json_result['category']['childseries'],然后循环进入它

 foreach ($json_result['category']['childseries'] as $data) {
     foreach($data as $key => $val) {
        echo "$key=>$val" . "<br>";
    }
 }

这将outout

series_id=>SEDS.PATCB.RI.A
name=>All petroleum products total consumption, Rhode Island
f=>A
units=>Billion Btu
updated=>22-APR-13 12.40.53 PM
series_id=>SEDS.PATCB.TN.A
name=>All petroleum products total consumption, Tennessee
f=>A
units=>Billion Btu
updated=>22-APR-13 12.40.53 PM
series_id=>SEDS.PATCB.NY.A 
//and so on

现场样品

于 2013-06-08T15:19:19.580 回答