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

时间:2012-02-25 21:13:37

标签: php arrays algorithm

是否有一种简单的方法可以获取1到15范围内的数字列表。并用短划线代替连续数字。

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

1 2 3 5 6 7 10 12

输出

1 - 3, 5 - 7, 10, 12

2 个答案:

答案 0 :(得分:7)

<?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]);
  }

答案 1 :(得分:6)

$n = array (1, 2, 4, 5, 7, 8, 10, 11, 12, 13, 14, 16, 17);
$lastindex = count($n)-1;
foreach($n as $k => $i)
{
    if($k == 0) echo $i;
    elseif($i != $n[$k-1]+1) echo ', ' . $i;
    elseif($k == $lastindex || $i+1 != $n[$k+1]) echo ' - ' . $i;
}

爆炸的功能:

http://codepad.org/DKztLGhe

function shorten( $numbers ){
  $a = explode(' ',$numbers);
  $lastindex = count($a)-1;
  $s = '';
  foreach( $a as $i => $n ){
    if( $i == 0 )                                    $s .=       $n;
    else if( $a[$i-1]+1 != $n )                      $s .=  ', '.$n;
    else if( $i == $lastindex || $n+1 != $a[$i+1] )  $s .= ' - '.$n;
  }
  return $s;
}

print_r(shorten('').'<br>');
print_r(shorten('1').'<br>');
print_r(shorten('1 2').'<br>');
print_r(shorten('1 3').'<br>');
print_r(shorten('1 3 4 6').'<br>');
print_r(shorten('1 3 4 6 7').'<br>');
print_r(shorten('1 2 3 4 5').'<br>');
print_r(shorten('1 2 3 5 6 10 12 13').'<br>');