所以,我有一个具有这种结构的值的数组:
$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密集度较低)?
感谢。
答案 0 :(得分:3)
下面的代码应该填补空白,如果你预计差距会超过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));
答案 1 :(得分:2)
这是你的答案,我已经测试过,它运作得很好:
<?php
$values = array(
"2012-01-01 00:15:00" => "0.01",
"2012-01-01 00:30:00" => "0.34",
"2012-01-01 01:00:00" => "0.23",
);
$values2 = array();
$passFirst = 0;
$difference = 60*15;
foreach ($values as $k => $v) {
$tempTime = date('Y-m-d H:i:s', strtotime($k) -$difference);
if (!isset($values[$tempTime]) && $passFirst) {
$values2[$tempTime] = '0.00';
}
$values2[$k] = $v;
$passFirst = 1;
}
/* The next two lines are for debugging, remove or comment after that */
print('<pre>');
print_r($values2);