Converting array elements into range in php

2019-02-09 19:03发布

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 I’m trying to convert it into range for e.g in above case it would be:

11-12,15-18,22-24

I don’t have any idea how to convert it into range.

标签: php arrays range
7条回答
趁早两清
2楼-- · 2019-02-09 19:54

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

查看更多
登录 后发表回答