Geo C.
Geo C.

Reputation: 755

How to implement a performant search of dates intervals in an array of dates?

Having this array :

array (size=1)
  24 => 
    array (size=7)
      'user_id' => int 24
      'date_clicked' => 
        array (size=3)
          0 => int 1382867319
          1 => int 1382867419
          2 => int 1382940698
      'ip' => string '127.0.0.1' (length=9)
      'email' => string 'test' (length=8)
      'name' => string 'test' (length=7)
      'request' => string 'test content' (length=12)
      'faked_clicks' => 
        array (size=3)
          0 => int 1382867319
          1 => int 1382867419
          2 => int 1382940698  

Here is my implementation that adds the faked_clicks array based on the date clicked array :

foreach($parsedUserClicks as $k => $v) {
    foreach($v['date_clicked'] as $kk => $vv) {
        $rangeHigh = range($vv, $vv+(60*60*24));
        $checkHigh = array_intersect($v['date_clicked'], $rangeHigh );
        if(count($checkHigh) >= 3) {
            $parsedUserClicks[$k]['faked_clicks'] = $checkHigh;
        }
    }
} 

The thing is that , by using array_intersect , it's taking quite a long time make a search only for 3 timestamps .

What I want to achieve is to get all 3 dates that are in an interval of 1 day . But my search is too slow (5 seconds for this simple search) . Any algorith i could use for this type of search ?

P.S. : I know i should not use such a big range to intersect arrays (60*60*24) . But i can't seem to find another solution . Also the range might get bigger so this method eventually will drop .

Upvotes: 0

Views: 49

Answers (2)

Geo C.
Geo C.

Reputation: 755

The only solution i could think of right now was to minimize the search to be made on days not on seconds . This is not a final answere , maybe someone else can give a proper search algorith for this type of search .

Upvotes: 0

Einacio
Einacio

Reputation: 3532

how about simply checking the values?

$dc_copy = $v['date_clicked'];
foreach($parsedUserClicks as $k => $v) {
    $checkHigh = array();
    foreach($v['date_clicked'] as $kk => $vv) {
        $rangeHigh = $vv+(60*60*24);
        foreach($dc_copy as $v2){
            if($v2 >= $vv && $v2 <= $rangeHigh){
                $checkHigh[] = $v2;
            }
        }
        if(count($checkHigh) >= 3) {
            $parsedUserClicks[$k]['faked_clicks'] = $checkHigh;
        }
    }
} 

Upvotes: 1

Related Questions