我正在用PHP进行REST调用并返回JSON。我最终将其放入表中,但现在尝试输出该值以了解其实质。
我想进入变量的“数据”字段中有值。在我的示例中,它们将是"201807", 23.43
和"201806", 22.54
。这是属性“ data”的前两个值
我的代码如下:
<?php
$service_url = "http://api.eia.gov/geoset/?geoset_id=ELEC.PRICE.RES.M®ions=USA-AL,USA-AK,USA-AR&api_key=3a8b92cfaf3a21e2e990f228c9152eeb&out=json&start=2018";
$get_data = callAPI('GET', $service_url, false);
$response = json_decode($get_data);
foreach ($response as $r) {
echo $row->name;
echo $row->geoset_id;
}
?>
JSON如下所示:
{
"geoset": {
"geoset_id": "ELEC.PRICE.RES.M",
"setname": "Average retail price of electricity : residential : monthly",
"f": "M",
"units": "cents per kilowatthour",
"unitsshort": null,
"series": {
"USA-AK": {
"series_id": "ELEC.PRICE.AK-RES.M",
"name": "Average retail price of electricity : Alaska : residential : monthly",
"region": "USA-AK",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 23.43],
["201806", 22.54],
["201805", 22.16],
["201804", 21.61],
["201803", 21.47],
["201802", 21.11],
["201801", 21.67]
]
},
"USA-AL": {
"series_id": "ELEC.PRICE.AL-RES.M",
"name": "Average retail price of electricity : Alabama : residential : monthly",
"region": "USA-AL",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 12.28],
["201806", 12.41],
["201805", 12.49],
["201804", 12.79],
["201803", 12.65],
["201802", 12.29],
["201801", 11.59]
]
},
"USA-AR": {
"series_id": "ELEC.PRICE.AR-RES.M",
"name": "Average retail price of electricity : Arkansas : residential : monthly",
"region": "USA-AR",
"latlon": null,
"unitsshort": null,
"start": "200101",
"end": "201807",
"data": [
["201807", 9.98],
["201806", 9.99],
["201805", 9.89],
["201804", 10],
["201803", 10.47],
["201802", 9.8],
["201801", 9.36]
]
}
}
}
}
到目前为止,我得到的是NULL值。
答案 0 :(得分:0)
使用json_decode
后,结果将转换为对象类型。因此您应该执行以下操作:
$geoset = $response->geoset;
$geosetid = $geoset->geoset_id;
foreach ($geoset->series as $row) {
echo $row->name;
$data = $row->data; //this will produce the values as array
}
您的数据数组将如下所示:
Array
(
[0] => Array
(
[0] => 201807
[1] => 23.43
)
[1] => Array
(
[0] => 201806
[1] => 22.54
)
)
...
希望这会有所帮助! :)
答案 1 :(得分:0)
您的代码将永远无法使用,因为:
img
,但在内部使用了$response as $r
; $row
只有一个孩子: geoset 。没有$response
也没有$response->name
。如果需要 geoset_id ,则必须使用:$response->geoset_id
。
要实现这一目标:
“数据”字段中有一些我想输入变量的值
使用以下代码:
$response->geoset->geoset_id