Converting array elements into range in php

后端 未结 7 1784
时光说笑
时光说笑 2021-01-02 11:39

I’m working on an array of numeric values.

I have a array of numeric values as the following in PHP

11,12,15,16,17,18,22,23,24

And

相关标签:
7条回答
  • 2021-01-02 12:37

    http://ideone.com/lmd7SY

    This is my version folks. The algorithm is quite evident from the way I've coded it up, with comments at regular intervals. The approach was to divide the problem into sub-parts, and here's pseudo-code.

    Pass through the sorted array using a loop to detect break points. If the next and previous numbers are in a consequent progression of n+1, do nothing, else, note that a break point has now been detected. Track that break point by pushing the key of break into a new array. Using the data from the break point array, use the key information where the break points occur to loop through the initial array to build range values. Ensure a check for last iteration.

    $array = array(11,12,15,16,17,18,22,23,24);
    $break_start = array();
    
    //range finder
    for ($i=0; $i<sizeof($array); $i++) {
        $current = $array[$i]; 
        $previous = $array[$i-1];
        if ($current==($previous+1)) { 
            //no break points are found 
        } else { 
            //return break points with keys intact
            array_push($break_start, $i);
        }
    
    }
    
    for ($i=0; $i<sizeof($break_start); $i++) {
        $key = $break_start[$i];
        $next_key = $break_start[$i+1];
    
        //if last iteration
        if ($i==sizeof($break_start)-1) { 
            echo "Range: ".$array[$key]." - ".$array[count($array)-1]." \n"; 
            } 
        else { 
            echo "Range: ".$array[$key]." - ".$array[$next_key-1]." \n";    
            }
    }
    

    Pretty solid and hand coded in around 10 minutes.

    Works for larger sets as well, tried and test:

    $array = array(11,12,15,16,17,18,22,23,24,26,27,28,56,57,58);
    

    enter image description here

    0 讨论(0)
提交回复
热议问题