# 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)];
``````

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

``````\$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;
}
}
``````

© 2020-2024 STACKOOM.COM