PHP array How to elegantly convert 1,2,4,5,6,7,9,11 into a string like '1,2,4-7,9,11'?
过去多啦不再A梦
过去多啦不再A梦 2017-06-05 11:07:46
0
2
652

Like the title

There is a php array

[1,2,4,5,6,7,9,11]


[7,11,16,17,18,33,102,103,555]

Elegant conversion to

'1,2,4-7,9,11' 
'7,11,16-18,33,102-103,555'

What about such a string?

Thank you for your answer.

过去多啦不再A梦
过去多啦不再A梦

reply all(2)
我想大声告诉你

If you want to put consecutive numbers together, you can directly use array_reduce to calculate the results and then use implode to splice them into a string.

function array_hyphens($arr){
    return implode(',',array_reduce($arr,function($a,$num){
        if(!($len=count($a))) return array($num);
        @list($s,$e) =explode('-',$a[--$len]);
        if($s==$num-1 || (isset($e) && $e==$num-1)) $a[$len]=implode('-',array($s,$num));
        else array_push($a,$num);
        return $a;
    },array()));
}
echo array_hyphens([7,11,16,17,18,33,102,103,555]);
// 7,11,16-18,33,102-103,555

But I don’t understand your pattern. In your first example, 1 and 2 are not connected, but in your second example, 102 and 103 are connected. Is it a mistake or do you have special needs?

曾经蜡笔没有小新
  $a1=array(1,2,3,5,6,10,15,28,89,90,91,92,93);
  
      $count=count($a1);

      foreach ($a1 as $key => $value) {
        
        if(empty($a2)){
            $a2['min']=$value;
            $a2['max']=$value;
          

        }else{

           
            if(($value-$a2['max']==1)&&($key<>$count-1)){
                 $a2['max']=$value;

            }else{
                  if($a2['min']==$a2['max']){
                       $a3[]=$a2['min'];
                    
                  }else{
                       $a3[]=$a2['min'].'-'.$a2['max'];

                  }
               
                  $a2['min']=$value;
                  $a2['max']=$value;


            }


          }


        }
echo '<pre>';var_dump($a3);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template