user1267570
user1267570

Reputation: 211

Fill missing days in data

I have an array which looks like this:

$data = array(
    array('timestamp' => 1312776000, 'something' => 100), // data for 08.08.2011
    array('timestamp' => 1312862400, 'something' => 120), // data for 09.08.2011
    //  ????????                                          // data for 10.08.2011
    array('timestamp' => 1313035200, 'something' => 160), // data for 11.08.2011
    array('timestamp' => 1313121600, 'something' => 180), // data for 12.08.2011
    array('timestamp' => 1313208000, 'something' => 200), // data for 13.08.2011
    //  ????????                                          // data for 14.08.2011
    //  ????????                                          // data for 15.08.2011
    //  ????????                                          // data for 16.08.2011
    //  ????????                                          // data for 17.08.2011
    array('timestamp' => 1313640000, 'something' => 300), // data for 18.08.2011
);

How to identify "holes" and fill them with a subarray with 'something' => 0? As you can see, "holes" can be very large, that is why i was not able to solve this problem myself - my algorithm can fill only tiny "holes" (like 10.08.2011, but not 14.08.2011 -> 17.08.2011).

Upvotes: 2

Views: 288

Answers (3)

Stano
Stano

Reputation: 8949

It can be done this way:

$new = array();
$prev = reset($data);
while ($record = reset($data)) {
    while ($prev['timestamp'] < $record['timestamp']-86400) {
        $prev['timestamp'] += 86400;
        $prev['something'] = 0;
        $new[] = $prev;
    }
    $new[] = $record;
    $prev = $record;
    unset($data[key($data)]);
}
$data = $new;

echo '<pre>';
var_export($data);
echo '</pre>';

Upvotes: 1

ghbarratt
ghbarratt

Reputation: 11711

Another approach to consider:

$previous_d = false;
for($di=0; isset($data[$di]); $di++) {
    $d = $data[$di];
    if($previous_d && ($d['timestamp']-$previous_d['timestamp'])>86400) {
        $new_d = array('timestamp'=>$previous_d['timestamp']+86400,'something'=>0);
        array_splice($data,$di,0,array($new_d));
        $di--;
    }
    $previous_d = $d;
}

Upvotes: 1

ernie
ernie

Reputation: 6356

Your data appears to be sorted, and I'm guessing you want a single value per day. I've taken the lazy approach of writing a new output array, but you could append values to the existing array, and then sort by timestamp at the end.

I'd do something like this:

$outArray = array();
$lastTime = $data[0]['timestamp'] - 86400;
foreach($data as $values) {
    $dayDelta = ($values['timestamp'] - $lastTime)/86400;
    if ( $dayDelta != 1) {
        for ($i = $dayDelta-1; $i--; $i>0) {
            $pastDate = $values['timestamp'] - $i * 86400;
            $outArray[] = array('timestamp'=>$pastDate, 'something'=>0);
        }
    }
    $outArray[]=$values;
    $lastTime = $values['timestamp'];
}

Upvotes: 1

Related Questions