通过逗号和合并间隔将排序的数字数组内爆为字符串 [英] Implode sorted number array to string by commas and merge intervals
问题描述
我想内爆一个数组,但有一个区别.我想用 -
符号合并间隔.如何才能做到这一点?(数组是有序的!)
I would like to implode an array, but with one difference. I would like to merge intervals with a -
sign. How can this be done? (The array is ordered!)
示例:
array(1,2,3,6,8,9) => "1-3,6,8-9"
array(2,4,5,6,8,10) => "2,4-6,8,10"
推荐答案
这应该适合你:
首先,对于每次迭代,我们简单地将当前迭代次数附加到 $result
字符串:
First for every iteration we simply append the current number of the iteration to the $result
string:
$result .= $arr[$i];
此后,我们检查 while 循环中是否存在数组 (1) 中的下一个元素,并跟踪当前迭代中的数字 (2).我们这样做直到条件评估为假:
After this we check in a while loop if there exists a next element in the array(1) and it follows up the number from the current iteration(2). We do that until the condition evaluates as false:
//(1)Check if next element exists (2)Check if next element follows up the prev one
┌───────┴───────┐ ┌───────────┴────────────┐
while(isset($arr[$i+1]) && $arr[$i] + 1 == $arr[$i+1] && ++$range)
$i++;
然后我们检查我们是否有一个范围(例如 1-3
).如果是,那么我们将破折号和范围的结束编号附加到结果字符串中:
Then we check if we have a range (e.g. 1-3
) or not. If yes then we append the dash and the end number of the range to the result string:
if($range)
$result .= "-" . $arr[$i];
最后我们还检查我们是否在数组的末尾并且不再需要附加逗号:
At the end we also check if we are at the end of the array and don't need to append a comma anymore:
if($i+1 < $l)
$result .= ",";
代码:
<?php
$arr = array(1,2,3,6,8,9);
$result = "";
$range = 0;
for($i = 0, $l = count($arr); $i < $l; $i++){
$result .= $arr[$i];
while(isset($arr[$i+1]) && $arr[$i] + 1 == $arr[$i+1] && ++$range)
$i++;
if($range)
$result .= "-" . $arr[$i];
if($i+1 < $l)
$result .= ",";
$range = 0;
}
echo $result;
?>
输出:
1-3,6,8-9
这篇关于通过逗号和合并间隔将排序的数字数组内爆为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!