$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为标准数组,用来判断值是否存在 //a2用来存放已经被使用过的数 //a3为最后的结果数组 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; } //断开了,跳出循环 break; } } } } echo '<pre>'; var_dump($a3); die;
Split the array into 5 pieces, and then process the sub-arrays.
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...
Split the array into 5 pieces, and then process the sub-arrays.