查找连续数组密钥的最长跨度

时间:2010-06-24 10:21:31

标签: php

我有一个数组,它使用UNIX时间戳作为数组键。该阵列通常可以保存15分钟到几个小时的数据,但是只有几秒钟的条目有数据。

大部分数据都会分散开来,但连续几秒钟偶尔会出现数据跨度。我想做的是检索数组中最长连续秒数的第一个和最后一秒。

如果我有这个数组

Array
(
    [1276033307] => 119.0
    [1276033331] => 281.8
    [1276033425] => 28.2
    [1276033431] => 88.2
    [1276033432] => 196.2
    [1276034207] => 205.5
    [1276034226] => 73.8
    [1276034227] => 75.8
    [1276034228] => 77.8
    [1276034230] => 79.8
)

我要么需要密钥1276034226和1276034228,要么返回以下数组。

Array
(
    [1276034226] => 73.8
    [1276034227] => 75.8
    [1276034228] => 77.8
)

2 个答案:

答案 0 :(得分:2)

修改

$array = array(
    1276033307 => 119.0,
    1276033331 => 281.8,
    1276033425 => 28.2,
    1276033431 => 88.2,
    1276033432 => 196.2,
    1276034207 => 205.5,
    1276034226 => 73.8,
    1276034227 => 75.8,
    1276034228 => 77.8,
    1276034230 => 79.8,
);

$finalArray = array();
foreach($array as $k => $v){
    $tempArrays = array();
    $index = 0;
    while(isset($array[$k + $index])){
        $tempArrays[$k+$index] = $array[$k+$index++];
    }

    if(count($tempArrays) > count($finalArray))
        $finalArray = $tempArrays;
}

print_r($finalArray);

输出相同......

<强> ORIGINAL:

注意:仅记录第一次出现的最长跨度。

$array = array(
    1276033307 => 119.0,
    1276033331 => 281.8,
    1276033425 => 28.2,
    1276033431 => 88.2,
    1276033432 => 196.2,
    1276034207 => 205.5,
    1276034226 => 73.8,
    1276034227 => 75.8,
    1276034228 => 77.8,
    1276034230 => 79.8,
);

$longspan = 0;
foreach($array as $k => $v){
    $index   = 1;
    while(isset($array[$k+$index])){
        $index++;
    }

    $curspan = --$index;

    if($curspan > $longspan){
        $longspan = $curspan;
        $start    = $k;
    }
}

for($i=0; $i <= $longspan; $i++)
    $results[$start + $i] = $array[$start + $i];

print_r($results);

输出:

Array ( 
  [1276034226] => 73.8 
  [1276034227] => 75.8 
  [1276034228] => 77.8
) 

答案 1 :(得分:1)

这段代码在一个循环中完成(即贪婪算法):

$array = array(
    1276033307 => 119.0,
    1276033331 => 281.8,
    1276033425 => 28.2,
    1276033431 => 88.2,
    1276033432 => 196.2,
    1276034207 => 205.5,
    1276034226 => 73.8,
    1276034227 => 75.8,
    1276034228 => 77.8,
    1276034230 => 79.8,
);

$long_arr = array();
$curr_arr = array();
$last_key = -1;

foreach($array as $k => $v) {
    if ($k != $last_key + 1) {
        $curr_arr = array();
    }
    $curr_arr[$k] = $v;
    if (count($curr_arr) > count($long_arr)) {
        $long_arr = $curr_arr;
    }
    $last_key = $k;
}

print_r($long_arr);