phpdate-rangesequentialhyphenationconsolidation

Reduce array of month names by creating hyphenated expressions from consecutive months


I have an array like:

Array
(
    [0] => Jan
    [1] => Feb
    [2] => Mar
    [3] => Apr
    [4] => May
    [5] => Jun
    [6] => Sep
    [7] => Oct
    [8] => Dec
)

I need to convert it to

Array
(
    [0] => "Jan - Jun"
    [1] => "Sep - Oct"
    [2] => "Dec"
)

The months will always be in order, but since the array is dynamic, I can't think of a good efficient way to this, other than converting each month to number with date_parse and then combine with the months around it! but I am really confused as to how to do this, any ideas?


Solution

  • How about something like this:

    function findConsecutiveMonths(array $input) {
        // Utility list of all months
        static $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                               'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    
        $chunks = array();
    
        for ($i = 0; $i < 12; $i++) {
            // Wait until the $i-th month is contained in the array
            if (!in_array($months[$i], $input)) {
                continue;
            }
    
            // Find first consecutive month that is NOT contained in the array
            for ($j = $i + 1; $j < 12; $j++) {
                if (!in_array($months[$j], $input)) {
                    break;
                }
            }
    
            // Chunk is from month $i to month $j - 1
            $chunks[] = ($i == $j - 1) ? $months[$i] : $months[$i] .' - '. $months[$j - 1];
    
            // We know that month $j is not contained in the array so we can set $i
            // to $j - the search for the next chunk is then continued with month
            // $j + 1 because $i is incremented after the following line
            $i = $j;
        }
    
        return $chunks;
    }
    

    Demo: http://codepad.viper-7.com/UfaNfH