简体   繁体   English

从php访问json中的对象

[英]Accessing object in json from php

It's been a while since I've done this, and I'm clearly missing some critical piece.我已经有一段时间没有这样做了,我显然错过了一些关键部分。 I hope one you all can set me straight.我希望你们都能让我直截了当。

I have a json file that I'm decoding and I was hoping it was a simple task to access the data for a specific date.我有一个正在解码的 json 文件,我希望访问特定日期的数据是一项简单的任务。 Here's what I've done so far.这是我到目前为止所做的。

$solardata = file_get_contents('solar.json');
$solarjson = json_decode("$solardata");
$production = $solarjson->{'2019-01-24 11:00:00'};
echo "$production";

The $production variable is always empty. $production 变量始终为空。 For reference the solar.json file starts out like this:作为参考,solar.json 文件是这样开始的:

{"powerDetails":{"timeUnit":"QUARTER_OF_AN_HOUR","unit":"W","meters":[{"type":"Production","values":[{"date":"2019-01-24 11:00:00","value":273.5632},{"date":"2019-01-24 11:15:00","value":405.8625},{"date":"2019-01-24 11:30:00","value":558.6771},

A var_dump($solarjson) starts out like this: var_dump($solarjson) 开始是这样的:

object(stdClass)#321 (1) { ["powerDetails"]=> object(stdClass)#3 (3) { ["timeUnit"]=> string(18) "QUARTER_OF_AN_HOUR" ["unit"]=> string(1) "W" ["meters"]=> array(1) { [0]=> object(stdClass)#4 (2) { ["type"]=> string(10) "Production" ["values"]=> array(316) { [0]=> object(stdClass)#5 (2) { ["date"]=> string(19) "2019-01-24 11:00:00" ["value"]=> float(273.5632) } [1]=> object(stdClass)#6 (2) { ["date"]=> string(19) "2019-01-24 11:15:00" ["value"]=> float(405.8625) } [2]=> object(stdClass)#7 (2) { ["date"]=> string(19) "2019-01-24 11:30:00" ["value"]=> float(558.6771) }

The server error log says:服务器错误日志说:

Undefined property: stdClass::$2019-01-24 11:00:00 in /home/......

Are the ojects I'm trying to access inside an array that I still need to loop through?我试图访问的对象是否仍然需要循环访问? I was dreaming that I could avoid all that with a simple object request, as I look for specific data, but as I said, I'm pretty rusty.我梦想着我可以通过一个简单的对象请求来避免所有这些,因为我正在寻找特定的数据,但正如我所说,我很生疏。 Thanks for your help.谢谢你的帮助。

$solardata = file_get_contents('solar.json');
$solarjson = json_decode("$solardata");
$production = $solarjson['powerDetails']['meters'][0]['values']['date'];
echo "$production";`

this OUTPUT '2019-01-24 11:00:00';此输出 '2019-01-24 11:00:00';

You may also modify the content by :您还可以通过以下方式修改内容:

$solardata = file_get_contents('solar.json');
$solarjson = json_decode("$solardata");
$solarjson['powerDetails']['meters'][0]['values']['date'] = date(y-m-d);
echo $solarjson['powerDetails']['meters'][0]['values']['date'];`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM