Converting array elements into range in php

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

    If we have previous item and current item is not next number in sequence, then we put previous range (start-prev) in output array and current item will be start of next range, if we don't have previous item, then this item is the first item and as mentioned before - first item starts a new range. newItem function returns range or sigle number if there is no range. If you have unsorted array with repeating numbers, use sort() and array_unique() functions.

    $arr = array(1,2,3,4,5,7,9,10,11,12,15,16);
    
    function newItem($start, $prev)
    {
        if ($start == $prev)
        {
            $result = $start;
        }
        else
        {
            $result = $start . '-' . $prev;
        }
    
        return $result;
    }
    
    foreach($arr as $item)
    {
        if ($prev)
        {
            if ($item != $prev + 1)
            {
                $newarr[] = newItem($start, $prev);
                $start = $item;
            }
        }
        else
        {
            $start = $item;
        }
        $prev = $item;
    }
    
    $newarr[] = newItem($start, $prev);
    
    echo implode(',', $newarr);
    

    1-5,7,9-12,15-16

提交回复
热议问题