【发布时间】:2017-09-21 14:51:26
【问题描述】:
好吧,我被难住了。
我尝试了许多不同的方法,我花了好几个小时寻找我的确切情况无济于事,或者我累了和失明了。
这是使用 file_get_contents() 从 URI 中提取的原始 json:
{"id":"XXX","name":"Customer1","os":"CentOS Linux 7.3.1611 Core","cpu_type":"Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz","networking_v4":[{"addr":"xxx.xxx.xxx.xxx","if":"eth0"}],"networking_v6":[{"addr":"xxxx","if":"eth0"},{"addr":"xxxx","if":"eth0"}],"agent_version":0.96,"status":"up","last_update":1505949230,"first_update":1500588943,"notifications_count":8,"ip_whois":{"ip":"xxx.xxx.xxx.xxx","hostname":"xxx","city":"Garwood","region":"New Jersey","country":"US","loc":"xxx","org":"AS20473 Choopa, LLC","postal":"xxx"},"additional_fields":[{"value":"xxx","key":"Datacenter"},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""}]}
正如您所见,这是一个非常简单的请求,我拥有所有数据,除了那些嵌套在networking_v4 和networking_v6 中的数据。
我试图像这样访问那些:
'ipv4' => $json->networking_v4->addr,
'ipv4dev' => $json->networking_v4->if,
'ipv6' => $json->networking_v6->addr,
'ipv6dev' => $json->networking_v6->if,
以下是完整代码的完整快照:
$content = file_get_contents($url);
$json = json_decode($content);
$server_lastupd = $json->last_update;
$server_firstupd = $json->first_update;
$server = array(
'id' => $json->id,
'name' => $json->name,
'os' => $json->os,
'cputype' => $json->cpu_type,
'ipv4' => $json->networking_v4->addr,
'ipv4dev' => $json->networking_v4->if,
'ipv6' => $json->networking_v6->addr,
'ipv6dev' => $json->networking_v6->if,
'status' => $json->status,
'lastupd' => $json->$server_lastupd,
'firstupd' => $json->$server_firstupd,
'notifications' => $json->notifications_count,
'ip' => $json->ip_whois->ip,
'hostname' => $json->ip_whois->hostname,
'city' => $json->ip_whois->city,
'region' => $json->ip_whois->region,
'country' => $json->ip_whois->country,
'loc' => $json->ip_whois->loc,
'org' => $json->ip_whois->org,
'postal' => $json->ip_whois->postal,
'dctag' => $json->additonal_fields->dctag,
'source' => "XXX"
);
return $server;
所以我的问题是我似乎无法访问networking_v4 和networking_v6 中的子内容。
对此的任何帮助将不胜感激,它在昨晚的 6 个小时和今天更多的几个小时里让我难过,所以我放弃了,请有人给我亮灯! 非常感谢:)
【问题讨论】:
-
看到 json 中的括号了吗?
[]?这些是数组,而不是对象。 -
以后看看
var_dump($json)或者print_r($json)
标签: php json file-get-contents