2D PHP 数组,根据相似值连接值

2D PHP array, join values based on similar values

我有 PHP 数组,我用它来绘制图形

Json格式:

{"y":24.1,"x":"2017-12-04 11:21:25"},

{"y":24.1,"x":"2017-12-04 11:32:25"},

{"y":24.3,"x":"2017-12-04 11:33:30"},

{"y":24.1,"x":"2017-12-04 11:34:25"},

{"y":24.2,"x":"2017-12-04 11:35:35"},.........

{"y":26.2,"x":"2017-12-04 11:36:35"}, ->goes up for about a minute

{"y":26.3,"x":"2017-12-04 11:37:35"},.........

{"y":24.1,"x":"2017-12-04 11:38:25"},

{"y":24.3,"x":"2017-12-04 11:39:30"}

y=是温度,x 值是日期时间,

如您所见,温度不会经常变化,即使它最多只变化 0.4。但有时在长时间的相似值之后它会变化超过 0.4。

我想加入那些相似的值,所以图表不会有 200k 的相似值,只有那些 "important"。

我需要一个建议,如何制作或哪种算法最适合创建我想要的优化数组。

完美输出:

{"y":24.1,"x":"2017-12-04 11:21:25"},.........

{"y":24.1,"x":"2017-12-04 11:34:25"},

{"y":24.2,"x":"2017-12-04 11:35:35"},.........

{"y":26.2,"x":"2017-12-04 11:36:35"}, ->goes up for about a minute

{"y":26.3,"x":"2017-12-04 11:37:35"},.........

{"y":24.1,"x":"2017-12-04 11:38:25"}

有什么帮助吗?

正如您指定的那样php我假设您可以在输出端处理这个问题。

基本上,您需要像 "if the absolute value of the temperature exceeds the last temperature by so much, or the time is greater than the last time by x minutes, then let's output a point on the graph" 这样的逻辑。如果是这种情况,您可以通过以下方式获得结果:

$temps = array(); //your data in the question
$temp = 0;
$time = 0;
$time_max = 120; //two minutes
$temp_important = .4; //max you'll tolerate
$output = [];
foreach($temps as $point){
    if(strtotime($point['x']) - $time > $time_max || abs($point['y'] - $temp) >= $temp_important){
        // add it to output
        $output[] = $point;
    }
    //update our data points
    if(strtotime($point['x']) - $time > $time_max){
        $time = strtotime($point['x']);
    }
    if(abs($point['y'] - $temp) >= $temp_important){
        $temp = $point['y'];
    }
}
// and out we go..
echo json_encode($output);

嗯,这不完全是您的要求,好像温度在短时间内飙升然后立即下降,您需要更改您的逻辑 - 但请根据要求考虑。

如果您在输出端接收数据,我会在 javascript 中写一些东西来存储这些点 in/out 并使用相同的逻辑。您可能需要缓冲 2-3 个点才能做出决定。您的逻辑在这里执行一项重要任务,因此您希望封装它并确保您可以轻松指定参数。