"0.01", "2012-01-01 00:30:00" =-6ren">
gpt4 book ai didi

PHP:自动完成时间间隔

转载 作者:可可西里 更新时间:2023-11-01 00:49:34 24 4
gpt4 key购买 nike

所以,我有一个具有以下结构值的数组:

$values = array(
"2012-01-01 00:15:00" => "0.01",
"2012-01-01 00:30:00" => "0.34",
"2012-01-01 00:45:00" => "0.51",
);

如您所见,值之间的间隔为 15 分钟。有时我会得到缺失值,例如:

$values = array(
"2012-01-01 00:15:00" => "0.01",
"2012-01-01 00:30:00" => "0.34",
"2012-01-01 01:01:00" => "0.23",
);

在数组中以正确的顺序添加缺失的“2012-01-01 00:45:00” 和标准值(如“0.00”)的最佳方法是什么(CPU 密集度较低) ?

谢谢。

最佳答案

下面的代码应该填补空白,如果您预计空白会超过 30 分钟,我可以稍微延长一下

<?php
date_default_timezone_set('GMT');

$values = array(
"2012-01-01 00:15:00" => "0.01",
"2012-01-01 00:30:00" => "0.34",
"2012-01-01 01:31:00" => "0.23",
"2012-01-01 05:31:00" => "0.23",
"2012-01-02 01:31:00" => "0.23",
);

function process_values($values) {
$keys = array_keys($values);

$new_values = array();

$new_values[$keys[0]] = $values[$keys[0]];

for($i = 1; $i < count($keys); $i++) {
$timestamp = strtotime($keys[$i]);

$minute_difference = ($timestamp - strtotime($keys[$i - 1])) / 60;

$start_minutes = floor(date('i', strtotime($keys[$i - 1])) / 15) * 15;

for($k = 1; $k < floor($minute_difference / 15); $k++) {
$minutes = $start_minutes + $k * 15;

$formatted_date = date('Y-m-d H:' . str_pad($minutes % 60, 2, '0') . ':00', strtotime($keys[$i - 1]) + floor($minutes / 60) * 3600);

$new_values[$formatted_date] = '0.00';
}

$new_values[$keys[$i]] = $values[$keys[$i]];
}

return $new_values;
}

print_r(process_values($values));

关于PHP:自动完成时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10466883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com