$ranges = array(
array(9, 12),
array(1, 2),
array(60, 81),
array(10, 11),
array(79, 88),
);
function optimizeRangeArray($r) {
$flagarr = array();
foreach ($r as $range => $bounds) {
$flagarr = array_pad($flagarr, $bounds[1], false);
for ($i = $bounds[0]-1; $i < $bounds[1]; $i++) $flagarr[$i] = true;
}
$res = array(); $min = 0; $max = 0; $laststate = false;
$ctr = 0;
foreach ($flagarr as $state) {
if ($state != $laststate) {
if ($state) $min = $ctr + 1;
else {
$max = $ctr;
$res[] = array($min, $max);
}
$laststate = $state;
}
$ctr++;
}
$max = $ctr;
$res[] = array($min, $max);
return($res);
}
print_r(optimizeRangeArray($ranges));
输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 9
[1] => 12
)
[2] => Array
(
[0] => 60
[1] => 88
)
)
注意:这不适用于负整数!
或者像这样使用它
$rres = optimizeRangeArray($ranges);
$out = "<pre>Start End<br />";
foreach($rres as $range=>$bounds) {
$out .= str_pad($bounds[0], 9, ' ') . str_pad($bounds[1], 9, ' ') . "<br />";
}
$out .= "</pre>";
echo $out;
在浏览器中获取此信息
Start End
1 2
9 12
60 88