Dor*_*ron 6 php arrays reverse numbers range
我有这样一个数组:
array(0, 2, 4, 5, 6, 7, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99);
Run Code Online (Sandbox Code Playgroud)
我想把它作为以下字符串:
0, 2, 4-7, 90+
在我开始从头上拔毛之前有什么例子吗?
谢谢.
更新:
这是我在使用@Andy的代码后使用的最终解决方案,并对其进行了一些修改.
function rangeArrayToString($rangeArray, $max = 99) {
sort($rangeArray);
$first = $last = null;
$output = array();
foreach ($rangeArray as $item) {
if ($first === null) {
$first = $last = $item;
} else if ($last < $item - 1) {
$output[] = $first == $last ? $first : $first . '-' . $last;
$first = $last = $item;
} else {
$last = $item;
}
}
$finalAddition = $first;
if ($first != $last) {
if ($last == $max) {
$finalAddition .= '+';
} else {
$finalAddition .= '-' . $last;
}
}
$output[] = $finalAddition;
$output = implode(', ', $output);
return $output;
}
Run Code Online (Sandbox Code Playgroud)
And*_*ndy 11
$first = $last = null;
$output = array();
foreach ($array as $item) {
if ($first === null) {
$first = $last = $item;
} else if ($last < $item - 1) {
$output[] = $first == $last ? $first : $first . '-' . $last;
$first = $last = $item;
} else {
$last = $item;
}
}
$output[] = $first == $last ? $first : $first . '+';
$output = join(', ', $output);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
852 次 |
最近记录: |