这是一个简单的版本,创建包含您的范围的 groups
<?php
$numbers = array(1,3,2,23,24,25,26,8);
sort($numbers);
$groups = array();
for($i = 0; $i < count($numbers); $i++)
{
if($i > 0 && ($numbers[$i - 1] == $numbers[$i] - 1))
array_push($groups[count($groups) - 1], $numbers[$i]);
else // First value or no match, create a new group
array_push($groups, array($numbers[$i]));
}
foreach($groups as $group)
{
if(count($group) == 1) // Single value
echo $group[0] . "\n";
else // Range of values, minimum in [0], maximum in [count($group) - 1]
echo $group[0] . " - " . $group[count($group) - 1] . "\n";
}
输出是
1 - 3
8
23 - 26
现在,如果您的范围的顺序很重要,就像您在问题中描述的那样,您仍然可以对您的组进行排序...从我所见,您希望范围首先是单个值吗?这可以通过添加来完成
function groupRanges($a, $b)
{
if(count($a) == 1)
if(count($b) == 1)
return 0; // equal
else
return 1; // so $b is considered less than
if(count($b) == 1)
return -1; // so $a is considered less than
return 0; // both are ranges, keep them there... could be adjusted to compare the size of each range
}
usort($groups, "groupRanges");
就在foreach 之前,输出变为:
1 - 3
23 - 26
8