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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何在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的数字,然后结合它周围的月份!但我真的很困惑如何做到一点,任何想法?

解决方法

这样的事情怎么样:

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

脚本宝典总结

以上是脚本宝典为你收集整理的如何在php中组合连续的月份名称?全部内容,希望文章能够帮你解决如何在php中组合连续的月份名称?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。