gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:31:57 24 4
gpt4 key购买 nike

我有一个像这样的数组:

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 中组合连续的月份名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com