PHP:在数组中查找下一个最接近的月份

PHP: Find the next closest month in Array

给定一个如下所示的数组:

$months = array("mar","jun","sep","dec");

当前月份:

$current_month = date("m");

有没有办法找到下一个离当前月份最近的月份?

例如:

只需要将所有的月份相加,打印出下一个蛾子的位置即可。

<?php
$months = array("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec");
$current_month = date("m");

// The next moth must be the current month + 1 but as the index start from 0 we dont need to add + 1
// So we print 
echo $months[ $current_month % count($months)]; 

因为数组的位置是从0开始的所以不需要加+1

假设你想得到当前季度的最后一个月,你可以这样做:

$monthName = ["mar", "jun", "sep", "dec"][floor((date('n') - 1) / 3)];

我喜欢@Rizier123 的解决方案,所以我想写一个实现。

首先,让我们将月份数组转换为代表月份的数值。我们将保留文本作为关键,以便最终使匹配过程更容易。如果你能控制那几个月,那就很简单了:

$months = [ 'mar' => 3, 'jun' => 6, 'sep' => 9, 'dec' => 12];

如果您无法控制数组,您需要 运行 通过 array_map() 并使用日期进行转换:

$month_keys = $months;

$months = array_map( function( $month ) {
    return date( 'm', strtotime( $month ) );
}, $months );

$months = array_combine( $month_keys, $months );

然后让我们在数组中找到下一个最接近的值:

$closest_month = null;

foreach ( $months as $month_text => $month_num ) {
    if ( $current_month <= $month_num ) {
        $closest_month = $month_text;
        break;
    }
}

$closest_month 现在应该符合您问题中列出的所有条件。