繁体   English   中英

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

[英]PHP: Find the next closest month in Array

给定一个看起来像这样的数组:

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

和当前月份:

$current_month = date("m");

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

例如:

  • 如果当前月份为5月,则结果应为“ jun”
  • 如果当前月份为4月,则结果应为“ jun”
  • 如果当前月份为3月,则结果应为“ mar”
  • 如果当前月份是十月,则结果应为“ dec”

假设您要获取当前季度的最后一个月,可以这样进行:

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

只需添加所有月份并打印下一个飞蛾的位置。

<?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

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

首先,让我们将months数组转换为代表月份的数值。 我们将保留文本作为关键,以简化匹配过程。 如果您可以控制那几个月,那就很简单了:

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

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

$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应该符合您问题中列出的所有条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM