如何创建从一个数组的日期范围?
我有包含的各个时间点的特定值的值的JSON文件。目前,它的混乱和包含的重复了很多的。我想通过组织重复为日期范围内把它清理干净。
I have a JSON file containing the values of a particular value at various points of time. Currently, it's messy and contains a lot of duplicates. I'd like to clean it up by organizing the duplicates into a date range.
JSON文件的结构如下:
The JSON file is structured as follows:
[
{
"value": ".298",
"time": "21 May 2015 1:18:06 AM"
},
[...]
{
"value": ".298",
"time": "21 May 2015 12:15:07 PM"
},
{
"value": ".046",
"time": "21 May 2015 12:20:08 PM"
},
[...]
{
"value": ".046",
"time": "21 May 2015 12:30:15 PM"
},
{
"value": ".004",
"time": "22 May 2015 8:55:06 PM"
},
[...]
{
"value": ".004",
"time": "22 May 2015 9:45:06 PM"
}
]
和想我的输出:
21/05 01:19:06 AM to 21/05 12:15:07 PM, value: .298
21/05 12:25:08 PM to 21/05 12:30:15 PM, value: .046
22/05 09:40:06 PM to 22/05 09:45:06 PM, value: .004
这是code我到目前为止有:
This is the code I have so far:
foreach ($json as $sub) {
if (isset($value)) {
if ($value == $sub['value'] || $value == NULL) {
$range[$i][] = [strtotime($sub['time']), $sub['value']];
}
else {
$i++;
}
}
$value = $sub['value'];
}
foreach ($range as $daterange) {
$begin = $daterange[0][0];
$end = $daterange[count($daterange)-1][0];
printf('%s to %s, value: %s',
date('d/m h:i:s A', $begin),
date('d/m h:i:s A', $end),
$daterange[0][1]
);
echo "<br/>";
}
在code我张贴的作品的大部分,但与大型阵列包含空值打交道时,它似乎有问题。由于在重复仍然存在。
The code I posted works for the most part, but when dealing with large arrays that includes null values, it seems to have issues. As in the duplicates are still there.
我该如何解决?我敢肯定,这哈克方法可以提高使用DateTime类多很多;我希望有人能告诉我它是如何做。
How can I fix it? I'm sure this hacky approach can be improved a lot more using DateTime class; I hope someone can show me how it's done.
我不格式化输出。我觉得你可以自己
I don't format the output. I think you can yourself
$array = json_decode($str);
$starttime = $endtime = $array[0]->time;
$value = $array[0]->value;
foreach ($array as $item)
if ($item->value == $value) $endtime = $item->time;
else {
echo "$starttime to $endtime, value: $value\n";
$starttime = $endtime = $item->time;
$value = $item->value;
}
echo "$starttime to $endtime, value: $value\n";
使用有问题的输出数据:
With data in question output:
21 May 2015 1:18:06 AM to 21 May 2015 12:15:07 PM, value: .298
21 May 2015 12:20:08 PM to 21 May 2015 12:30:15 PM, value: .046
22 May 2015 8:55:06 PM to 22 May 2015 9:45:06 PM, value: .004