如何在php中组合连续的月份名称?

时间:2013-07-12 12:35:45

标签: php

我有一个像:

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

我需要将其转换为

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

这几个月总是井井有条,但由于阵列是动态的,我想不出一个好的有效方法,除了将每个月转换为使用date_parse的数字,然后结合它周围的月份!但我真的很困惑如何做到这一点,任何想法?

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

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

演示:http://codepad.viper-7.com/UfaNfH

答案 1 :(得分:0)

这应该这样做:

function combine_months($months) {
    $all_months = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    $target = array();
    $start = null;
    for ($i = 0; $i<12; $i++) {
        if (!in_array($all_months[$i], $months) && $start != null) {
            if ($start == null) {
                $target[] = $all_months[$i-1];
            }
            else {
                $target[] = sprintf("%s - %s", $start, $all_months[$i-1]);
            }
            $start = null;
        }
        elseif ($start == null) {
            $start = $all_months[$i];
        }
    }
    if ($start != null) {
        $target[] = $start;
    }
    return $target;
}

$test = combine_months(array("Jan","Feb","Mar","Apr","May","Jun","Sep","Oct","Dec"));
var_dump($test);

迭代所有可用月份,记住第一个月,在缺少一个月时添加到目标数组。