$arr = [2,3,4,5,8,10,11,12,13,16,19];
Convert to string
2-5, 8, 10-13, 16, 19
My personal idea is to select 8 16 19 that do not rely on both sides, and then select a maximum and minimum value from 2 3 4 5.
Note down the starting point value and scan backward. If it is continuous, continue backward. Otherwise, note down the end point value and get a beg-end or beg. continue...
$arr=array(2,3,4,5,8,10,11,12,13,16,19);
//最大值
$max=max($arr);
//求和
$sun=array_sum($arr);
//排序
asort($arr);
//a1為標(biāo)準(zhǔn)數(shù)組,用來判斷值是否存在
//a2用來存放已經(jīng)被使用過的數(shù)
//a3為最后的結(jié)果數(shù)組
foreach ($arr as $key => $value) {
$a1[$value]=$value;
}
foreach ($arr as $key => $value) {
if(!isset($a2[$value])){
$start=$value;
$end=$value;
$a2[$value]=$value;
for($i=0;$i<$sun;$i++){
$end = $end+1;
if(isset($a1["$end"])){
$a2[$end]=$end;
}else{
$end =$end-1;
if($start==$end){
$a3 []= $start;
}else{
$a3 []= $start."-".$end;
}
//斷開了,跳出循環(huán)
break;
}
}
}
}
echo '<pre>';
var_dump($a3);
die;