Converting array elements into range in php

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

    You have to code it yourself ;-)

    The algorithm is quite simple:

    • Iterate over the items.
    • Remember the previous item and the start of the range.
    • For each item (except the first one) check:
      • If currentItem = prevItem + 1 then you haven't found a new range. Continue.
      • Otherwise your range has ended. Write down the range. You have remembered the start of the range. The end is the previous item. The new range starts with the current item.
      • The first item always starts a new range. Remember this one as start of the range.
    • Don't forget to write down the current range when leaving the loop.

提交回复
热议问题