Converting array elements into range in php

后端 未结 7 1792
时光说笑
时光说笑 2021-01-02 11:39

I’m working on an array of numeric values.

I have a array of numeric values as the following in PHP

11,12,15,16,17,18,22,23,24

And

7条回答
  •  有刺的猬
    2021-01-02 12:19

    I have used this one before, it does the trick.

    Takes as input a comma separated string of numbers. Call to sort could be ignored if numbers are guaranteed to be sorted already.

    function range_string($csv)
    {
        // split string using the , character
        $number_array = array_map('intval', explode(',', $csv));
        sort($number_array);
    
        // Loop through array and build range string
        $previous_number = intval(array_shift($number_array)); 
        $range = false;
        $range_string = "" . $previous_number; 
        foreach ($number_array as $number) {
          $number = intval($number);
          if ($number == $previous_number + 1) {
            $range = true;
          }
          else {
            if ($range) {
              $range_string .= "-$previous_number";
              $range = false;
            }
            $range_string .= ",$number";
          }
          $previous_number = $number;
        }
        if ($range) {
          $range_string .= "-$previous_number";
        }
    
        return $range_string;
    }
    
    $csv_string = "11,16,12,17,18,15,22,23,24";
    print range_string($csv_string); // 11-12,15-18,22-24
    

提交回复
热议问题