有没有一种简单的方法可以获取 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/