Implode sorted number array to string by commas and merge intervals

后端 未结 3 1662
不思量自难忘°
不思量自难忘° 2020-12-06 22:33

I would like to implode an array, but with one difference. I would like to merge intervals with a - sign. How can this be done? (The array is ordered!)

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 23:02

    There is no function like this, therefore you will need to create one yourself. I just created a sample function how this may look like, there are many possible solution for this (Did not try if it actually works, as I do not have a webserver in reach atm)

     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));
    ?>
    

提交回复
热议问题