将数组中的破损序列分组

问题描述 投票:0回答:1

我需要对残破的系列进行分组。

//Example
$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
//You see numbers are not continuous here.
//Therefore i need to group the above array to seek the below output

预期输出

Series 1 : from 1 to 3
Series 2 : 5
Series 3 : 7 and 8
Series 4 : 11 and 12
Series 5 : 15

在上面的示例中,您可以看到,系列1从1到3分组(因为有两个以上的值),而在系列2和5中,由于没有连续性,所以显示了一个值。在系列3和4中,它显示2个值,两个连续的值。

我尝试过的

function groupSeries($mainArray, $comboArr=array()) {
   $getRange = range(min($mainArray), max($mainArray)); //Expected Range
   $diffArr  = array_diff($getRange, $mainArray); //Difference of what is expected
   $ranges   = array();
   $initiateKey = 0;
   foreach($diffArr as $indKey=>$indVal) {
      if(!empty($mainArray[$initiateKey])) {
         $ranges[] = range($mainArray[$initiateKey], $getRange[$indKey-1]);
         $initiateKey = $indKey;
      }
   }
   return showRanges($ranges);
}
function showRanges($getRanges) {
   $i = 1;
   foreach($getRanges as $indRange) {
     $arrCount = count($indRange);
     echo "Series $i : ";
     switch($arrCount) {
        case 1 : echo $indRange[0]; break;
        case 2 : echo $indRange[0]." and ".$indRange[1]; break;
        default: echo "From ".min($indRange)." to ".max($indRange); break;
     }
     $i++;
     echo "\n";
   }
}

$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
groupSeries($seriesArray);

上述数组序列失败,当前输出为

Series 1 : From 1 to 3
Series 2 : 5
Series 3 : 8
Series 4 : From 9 to 15

以上试验在某些情况下有效,但在许多情况下均失败。请通过纠正我来帮助我。

提前感谢

php arrays series numeric
1个回答
0
投票

您可以尝试以下代码吗?

$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
$result = array();

$indx = 0;
foreach($seriesArray as $key => $val){
    $tmp  = $seriesArray[$key];
    $next = (isset($seriesArray[$key+1]))? $seriesArray[$key+1] : '';
    if($next != ''){
        if(!isset($result[$indx])) $result[$indx] = array();
        if(($tmp+1) == $next ){
            $result[$indx][] = $tmp;
        }else{
            $result[$indx][] = $tmp;
            $indx++;

        }
    }   
}
print_r($result);

0
投票

简单foreach()

$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
function checkConsec($seriesArray) {
    $array = [];
    $j = 0;
    foreach($seriesArray as $k=>$v){
        if(isset($seriesArray[$k+1]) && $seriesArray[$k]+1 == $seriesArray[$k+1]) {
            $array[$j][] = $v;
        }else{
            $array[$j][] = $v;
            $j++;
        }
    }
    return $array;
}
print_r(checkConsec($seriesArray));

https://3v4l.org/r1QXq

© www.soinside.com 2019 - 2024. All rights reserved.