我想内爆一个数组,但有一个不同之处。我想把间隔和-符号合并起来。这是如何做到的呢?(数组是有序的!)
示例:
array(1,2,3,6,8,9) => "1-3,6,8-9"
array(2,4,5,6,8,10) => "2,4-6,8,10"发布于 2015-11-23 15:27:51
这应该适用于你:
首先,对于每次迭代,我们只需将当前的迭代次数附加到$result字符串中:
$result .= $arr[$i];在此之后,我们签入一个while循环,如果数组(1)中存在下一个元素,它将跟踪当前迭代(2)中的数字。我们会这样做,直到条件计算为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)。如果是,则在结果字符串中追加范围的破折号和结束号:
if($range)
$result .= "-" . $arr[$i];最后,我们还检查是否位于数组的末尾,不再需要追加逗号:
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发布于 2015-11-23 15:15:51
$oldArray=array(2,4,5,6,8,10);
$newArray=array();
foreach($oldArray as $count=>$val){
if($count==0){
//begin sequencing
$sequenceStart=$sequenceEnd=$val;
}
if($val==$sequenceEnd+1){
$sequenceEnd=$val;
continue;
}else{
if($sequenceEnd==$val){
//do nothing
continue;
}
}
//new sequence begins
//save new sequence
if($sequenceStart==$sequenceEnd){
//sequnce is a single number
$newArray[]=$sequenceEnd;
}else{
$newArray[]=$sequenceStart.'-'.$sequenceEnd;
}
//reset sequence
$sequenceStart=$sequenceEnd=$val;
}
//new sequence begins
//save new sequence
if($sequenceStart==$sequenceEnd){
//sequnce is a single number
$newArray[]=$sequenceEnd;
}else{
$newArray[]=$sequenceStart.'-'.$sequenceEnd;
}
//reset sequence
$sequenceStart=$sequenceEnd=$val;
return implode(',', $newArray);发布于 2015-11-23 15:37:37
没有这样的功能,因此您需要自己创建一个函数。我刚刚创建了一个示例函数,它的样子,有许多可能的解决方案(没有尝试,如果它真的工作,因为我没有一个may服务器在reach atm)。
<?php
function implodeNumberArray($arr) {
$lastValue = NULL;
$o = "";
//For each value in array
foreach ($arr as $v) {
if(!is_null($lastValue)) {
//If the number is following, do not paste it
if(($lastValue+1) == $v) {
//Check if the - sign was already posted
if(!(stripos(strrev($o), '-') === 0)) {
// - sign not pasted, therefore paste it
$o .= "-";
}
} else {
//Check if there is a - sign at the end
if((stripos(strrev($o), '-') === 0)) {
// Has - => paste 'prevValue,value''
$o .= $lastValue . "," . $v;
} else {
//Check if there is a , sign at the end
if((stripos(strrev($o), ',') === 0)) {
// No - but , => paste 'value'
$o .= $v;
} else {
// No - and no , => paste ',value'
$o .= ",".$v;
}
}
}
} else {
$o = $v;
}
$lastValue = $v;
}
//Check if the implode has the last number set correctly
if((stripos(strrev($o), '-') === 0)) {
$o .= $lastValue;
}
return $o;
}
echo implodeNumberArray(array(1,2,3,6,8,9));
?>https://stackoverflow.com/questions/33874059
复制相似问题