如何在php中解码JSON数组

时间:2013-06-08 15:07:52

标签: php json

我是php新手,我很难从我的JSON对象中获取正确的数据。我不想从this JSON link

获取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,名称,单位和更新?

2 个答案:

答案 0 :(得分:2)

请使用:

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

如果查看json结构,您会看到childseries位于category内。因此,$json_result['category']['childseries']是访问所需阵列的方法。只需循环遍历即可获得所需的数据。

答案 1 :(得分: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

Live Sample