search

Home  >  Q&A  >  body text

php - Simple string processing, looking for ideas.

$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.

滿天的星座滿天的星座2808 days ago412

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-05-16 13:15:33

    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...

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:15:33

    $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;
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:15:33

    Split the array into 5 pieces, and then process the sub-arrays.

    reply
    0
  • Cancelreply