用逗号爆排序数字数组和字符串间隔合并 [英] Implode sorted number array to string by commas and merge intervals
问题描述
我要破灭的阵列,但有一点不同。我想用合并间隔 -
标志。如何才能做到这一点? (数组是有序的!)
例如:
阵列(1,2,3,6,8,9)=> 1-3,6,8-9
阵列(2,4,5,6,8,10)= GT; 2,4-6,8,10
这应该为你工作:
首先每次迭代我们只需追加迭代到 $结果的当前数量
字符串:
$结果= $改编[$ i]。
在此之后,我们检查在循环是否存在数组(1)下一个元素,它遵循从当前迭代(2)的数量。我们这样做,直到条件的计算结果为假:
//(1)检查下一个元素存在(2)检查下一个元素跟进的preV 1
┌───────┴───────┐┌───────────┴────────────┐
而(使用isset($改编[$ I + 1])及和放大器; $改编[$ i] + 1 == $改编[$ I + 1]安培;&安培; ++ $范围)
$ I ++;
然后我们检查,如果我们有一个范围(例如, 1-3
)或不。如果是的话那么我们追加短跑和范围的结束编号到结果字符串:
如果($范围)
。$结果= - 。 $改编[$ i];
最后,我们还要检查,如果我们在数组的末端,不需要再附加一个逗号:
如果($ I + 1< $ L)
$结果=;
code:
< PHP $ ARR =阵列(1,2,3,6,8,9);
$结果=;
$范围= 0; 为($ i = 0,$ L =计数($ ARR); $ I< $ L,$ I ++){ 结果$ = $改编[$ i]。 而(使用isset($改编[$ I + 1])及和放大器; $改编[$ i] + 1 == $改编[$ I + 1]安培;&安培; ++ $范围)
$ I ++; 如果($范围)
。$结果= - 。 $改编[$ i]; 如果($ i + 1的&下; $升)
$结果=; $范围= 0; } 回声$结果;?>
输出:
1-3,6,8-9
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!)
Examples:
array(1,2,3,6,8,9) => "1-3,6,8-9"
array(2,4,5,6,8,10) => "2,4-6,8,10"
This should work for you:
First for every iteration we simply append the current number of the iteration to the $result
string:
$result .= $arr[$i];
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++;
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 .= ",";
Code:
<?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;
?>
output:
1-3,6,8-9
这篇关于用逗号爆排序数字数组和字符串间隔合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!