将月数转换为年和月数


convert number of months to the number of years and months

我使用for循环来显示数字1-60:

for($i=0; $i<=60; $i++)

在循环中,我希望能够显示年和月的数量。例如:

1 month
2 months
3 month
...
1 year
1 year 1 month
1 year 2 month

等等…

我试过这个:

if(!is_float($i/12)) {
    $years = $i/12;
} else {
    $years = 'no';
}

这显示1在12个月,2在24个月,但没有之间

您可以将%/用于整数部分和除法的其余部分试试这个循环来显示的结果

 for($i=1; $i<=60; $i++){
        echo 'year = ' . floor($i/12) . ' month = ' .$i%12 . '<br />';
 }

在@scaisEdge 的帮助下,我使用了以下解决方案来完成我的代码

for($i=0; $i<=60; $i++) {
    if(!is_float($i/12)) {
        $years = floor($i / 12).' Year';
        $years = $years.($years > 1 ? 's' : '');
        if($years == 0) {
            $years = '';
        }
    }
    $months = ' '.($i % 12).' Month';
    if($months == 0 or $months > 1) {
        $months = $months.'s';
    }
    $display = $years.''.$months;
    echo '<option value="'.$i.'"';
    if($result["warrenty"] == $i) {
        echo 'selected="selected"';
    }
    echo '>'.$display.'</option>';
}
function yearfm($months)
{
  $str = '';
  if(($y = round(bcdiv($months, 12))))
  {
    $str .= "$y Year".($y-1 ? 's' : null);
  }
  if(($m = round($months % 12)))
  {
    $str .= ($y ? ' ' : null)."$m Month".($m-1 ? 's' : null);
  }
  return empty($str) ? false : $str;
}
for($x = 0; $x < 100; $x++)
{
  var_dump(yearfm($x));
}

另一个解决方案1:

for ($i=0; $i<=60; $i++) {
    $output = [];
    if ($i >= 12) {
        $years    = ($i - $i % 12) / 12;
        $output[] = $years > 1 ? $years . ' years' : $years . ' year';
    }
    if ($i % 12 > 0) {
        $monthsRest = $i % 12;
        $output[]   = $monthsRest > 1 ? $monthsRest . ' months' : $monthsRest . ' month';
    }
    echo implode(' ', $output);
}

另一种解决方案2:

for ($i=0; $i<=60; $i++) {
    $output    = [];
    $startDate = new DateTime();
    $endDate   = new DateTime('+' . $i . ' months');
    $interval  = $startDate->diff($endDate);
    $years     = $interval->format('%y');
    $months    = $interval->format('%m');
    if ($years > 0) {
        $output[] = $years > 1 ? $years . ' years' : $years . ' year';
    }
    if ($months > 0) {
        $output[] = $months > 1 ? $months . ' months' : $months . ' month';
    }
    echo implode(' ', $output);
}