在PHP中将数组元素转换为范围 [英] Converting array elements into range in php

查看:102
本文介绍了在PHP中将数组元素转换为范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一组数字值.

I’m working on an array of numeric values.

我在PHP中有一个数值数组,如下所示:

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.

推荐答案

您必须自己编写代码;-)

You have to code it yourself ;-)

算法非常简单:

  • 遍历所有项目.
  • 记住上一项和范围的开始.
  • 对于每个项目(第一个项目除外)进行检查:
    • 如果为currentItem = prevItem + 1,则您尚未找到新范围.继续.
    • 否则,您的范围已结束.写下范围.您已经记住了范围的开始.末尾是上一项.新范围从当前项目开始.
    • 第一个项目始终会开始一个新范围.记住这是该系列的开始.
    • 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.

      这篇关于在PHP中将数组元素转换为范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆