Converting array elements into range in php

后端 未结 7 1892
时光说笑
时光说笑 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:24

    The answer provided by Ali Gajani kept giving me "Illegal offset" warnings. So, because I figured somebody might want to use it as badly as I do, I'm posting my fixes here - though note that my fixes might be deemed silly by an advanced programmer - it does seem to work now with no issues.

    I replaced/tweaked two parts of the code. Below you will see what I added (marked in bold) and what was removed, which I commented (//).

    As near as I can tell, it was having trouble on the first pass because there was no "previous pass" to refer to (hence, it was balking at "$previous = $array[$i-1];") - and on the last pass for a similar reason. In that second instance, I simply moved "$next_key = $break_start[$i+1];" below the last iteration check.

    $break_start = array();
    
    //range finder
    for ($i=0; $i0) {
            $previous = $array[$i-1];
    }
    else {
            $previous = $current;
    }**
      //  $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

    If there are smarter ways to get this done, please advise. But I searched high and low for this - and figured someone else might also benefit. Another tip of the hat to Ali Gajani for his initial help.

提交回复
热议问题