【问题标题】:2D PHP array, join values based on similar values二维 PHP 数组,基于相似值连接值
【发布时间】:2018-02-16 22:30:54
【问题描述】:

我有用于绘制图形的 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 的相似值,而只有那些“重要”的值。

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

完美输出:

{"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 arrays optimization multidimensional-array mathematical-optimization


    【解决方案1】:

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

    基本上,您需要类似“如果温度的绝对值超过上一个温度这么多,或者时间比上一个时间大 x 分钟,那么让我们在图表上输出一个点”这样的逻辑。如果是这种情况,您可以通过以下方式获得结果:

    $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 中编写一些东西来存储这些点输入/输出并使用相同的逻辑。您可能需要缓冲 2-3 分才能做出决定。您的逻辑在这里执行一项重要任务,因此您需要封装它并确保您可以轻松指定参数。

    【讨论】:

    • 谢谢,它工作得很好......我只用这段代码就可以减少大约 60% 的数据。
    • 如果可行,请接受答案,但为了清楚起见,您也可以将最终代码发布为编辑
    猜你喜欢
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2010-10-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多