在 PHP 和 file_get_contents() 中使用 JSON 访问子节点

Accessing a child node using JSON within PHP and file_get_contents()

好吧,我被难住了。

我已经尝试了很多不同的方法,并且我花了好几个小时的大部分时间来搜索我的确切情况,但对我的确切情况无济于事,或者我累了,瞎了。

这是使用 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->networking_v4[0]->addr

networking_v4networking_v6 键都指向数组,因此您需要选择要查看的索引。前者只有一个元素,所以很容易选择索引0,但后者有多个元素,所以你需要弄清楚你想要哪个。

看起来它们嵌套在 [{"key':"value"},{"key":"value"}] 方括号中的数组中。您尝试过

ipv4 => $json->networking_v4[0]->addr,