如何从数组中提取数字序列?

时间:2015-03-17 14:59:26

标签: php arrays

我有一个无序的数字:

$ar1 = [101,4,320,1,2,3,45,46];

我想在该数组中提取最长的数字序列并将它们放在第二个数组中? 我尝试了 usort ,我得到了这个:

Array(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 45
[5] => 46
[6] => 101
[7] => 320
[8] => 321
[9] => 323)

但是如何提取最长的序列(在这种情况下,女巫是1,2,3,4)并放入另一个数组?

更新 这是一个代码:

function sub($a,$b)
{
if ($a == $b)
{
    return 0;
}
return ($a<$b)? -1:1;
}

$ar1 = ["101","4","320","321","323","1","3","2","45","46"];
$ar2 = [];
usort($ar1,"sub");
print_r($ar1);

所以我想用数组中最长的序列填充$ ar2 ...

1 个答案:

答案 0 :(得分:0)

我明白了:

$ar1 = [101,4,320,1,2,3,45,46,47];
sort($ar1);
$first = $ar1[0];//assign first (lowest) number
$i=0;
$ar2 = array(); //this array will contain all arrays of consecutive numbers
foreach($ar1 as $v){
    if($v-$first == 1){
        $ar2[$i][] = $v;
    }else{
        $i++;
        $ar2[$i] = array($v); //difference > 1, we set another array
    }
    $first = $v;
}
//now we look for the longest array
$max = 0;
$longest = array();
foreach($ar2 as $k=>$ar){
    $c = count($ar);
    if($c < $max){
        unset($ar2[$k]); //if it is not the longest, we discard it
    }else{
        $max = $c;
        $longest = $ar;
    }
}
echo"<pre>";
print_r($longest);
echo"</pre>";

收率:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

复制,粘贴,运行,享受!