我需要读取以下json数据,然后将每行数据打印到一个文件中。如何知道测量数据的大小?
{
"Location":{
"name":"rauco",
"Sensor":{
"sensor_type":"oxygen",
"sensor_id":0,
"logger_id":1,
"Measurement 0":{
"timestamp":1406865601,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 1":{
"timestamp":1406865661,
"oxygen":9.9,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 2":{
"timestamp":1406865721,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
答案 0 :(得分:0)
无论是谁设计(我不知道为什么我使用了设计这个词),这个数据结构都应该被取出并接受基础教育......然后再拍摄。
我不知道任何语言可能会期望字段或类或属性允许名称中的空格,即Measurement 0
,以及使其更加糟糕的原因是json数据应该是普遍可用的任何语言。
对于设计师:没有雪茄甚至没有旧的潮湿的stoggy!
然而,这至少可以帮助您解决问题。
它被编写为以PHPCLI脚本运行,但也可以用作网页。
<?php
// create the ridiculous json data you have to use
$j = '{
"Location":{
"name":"rauco",
"Sensor":{
"sensor_type":"oxygen",
"sensor_id":0,
"logger_id":1,
"Measurement 0":{
"timestamp":1406865601,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 1":{
"timestamp":1406865661,
"oxygen":9.9,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 2":{
"timestamp":1406865721,
"oxygen":10.2,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 3":{
"timestamp":1406865781,
"oxygen":10.4,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 4":{
"timestamp":1406865841,
"oxygen":10,
"temperature":12.5,
"depth":5,
"salinity":0,
"status":1
},
"Measurement 5":{
"timestamp":1406865961,
"oxygen":8.9,
"temperature":12.4,
"depth":5,
"salinity":0,
"status":1
}
}
}
}';
现在代码
$json = json_decode($j);
$x = 0;
while ( 1 ) {
$impossible_obj_name = "Measurement $x";
if ( isset( $json->Location->Sensor->{$impossible_obj_name}) ) {
echo sprintf( 'timestamp: %s, oxygen %s, temperature: %s, depth: %s, salinity: %s, status: %s'.PHP_EOL,
$json->Location->Sensor->{$impossible_obj_name}->timestamp,
$json->Location->Sensor->{$impossible_obj_name}->oxygen,
$json->Location->Sensor->{$impossible_obj_name}->temperature,
$json->Location->Sensor->{$impossible_obj_name}->depth,
$json->Location->Sensor->{$impossible_obj_name}->salinity,
$json->Location->Sensor->{$impossible_obj_name}->status);
$x++;
} else {
break;
}
}
它应该生成它作为输出,我意识到这可能不是你真正想要的最终结果,但它演示了你将不得不用来克服灾难性数据结构设计的语法。
timestamp: 1406865601, oxygen 10.2, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865661, oxygen 9.9, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865721, oxygen 10.2, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865781, oxygen 10.4, temperature: 12.4, depth: 5, salinity: 0, status: 1
timestamp: 1406865841, oxygen 10, temperature: 12.5, depth: 5, salinity: 0, status: 1
timestamp: 1406865961, oxygen 8.9, temperature: 12.4, depth: 5, salinity: 0, status: 1