So, I've an Array with values with this structure:
$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",
);
As you can see the interval between values is 15 minutes. Sometimes I get missing values for example:
$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",
);
What's the best way (less CPU intensive) to add the missing"2012-01-01 00:45:00" in the right order in the array and a standard value like "0.00"?
Thanks.
The code below should fill in the gaps, I can extend it a little bit, if you anticipate the gaps would exceed 30 minutes
<?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));
Here is your answer, I've tested it and it works just fine:
<?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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With