php - 缩短连续数字之间带有连字符的数字列表

标签 php arrays algorithm

有没有一种简单的方法可以获取 1 - 15 范围内的数字列表。并用破折号代替连续的数字。

例如,如果您有以下数字:

1 2 3 5 6 7 10 12

它会输出

1 - 3, 5 - 7, 10, 12

最佳答案

<?php
$n = array (1, 2, 3, 5, 6, 7, 10, 12);
sort ($n);   // If necessary.
$i = 0;
while ($i < count ($n))
  {
    if ($i != 0)
      print (", ");
    $rangestart = $i;
    print ($n [$i++]);
    while ($i < count ($n) && $n [$i] == $n [$i - 1] + 1)
      $i++;
    if ($i > $rangestart + 1)
      print (" - " . $n [$i - 1]);
  }

关于php - 缩短连续数字之间带有连字符的数字列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448129/

相关文章:

php - 按日和月统计(php)

javascript - jQuery 两列(一维)数组?

Python 字典的底层哈希数据结构

从浏览器而非 CLI 调用时 PHP 脚本失败

php - 有哪些为 Web 开发人员介绍数据库的好书

ios - 如何验证数组值是否已存在

php - json_decode 函数 php ://input return Invalid JSON Format

algorithm - Bubblesort 优于其他排序算法?

algorithm - 大溪流水库采样

php - 如何将 PHP 变量数组发送到 MySQL 数据库?