如何显示给定日期数组中的显示活动和非活动月份

时间:2015-01-12 10:45:19

标签: php function date compare

我需要一个显示有效和无效月份的php功能。

我的阵列:

$dates = array('2014-08','2014-09','2014-11','2014-12','2015-02',)

预期产出:

2014-08 Active   
2014-09 Active    
2014-10 Inactive    
2014-11 Active    
2014-12 Active    
2015-01 Inactive    
2015-02  Active

3 个答案:

答案 0 :(得分:0)

这应该适合你:

<?php

    $dates = array('2014-08', '2014-09', '2014-11', '2014-12', '2015-02');
    $begin = new DateTime($dates[0]);
    $end = new DateTime(end($dates) . "+1 month");
    $interval = new DateInterval('P1M');
    $daterange = new DatePeriod($begin, $interval ,$end);

    foreach($daterange as $date)
        echo $date->format("Y-m") . (in_array($date->format("Y-m") , $dates) ? " active" : " inactive") . "<br />"; 


?>

输出:

2014-08 active
2014-09 active
2014-10 inactive
2014-11 active
2014-12 active
2015-01 inactive
2015-02 active

答案 1 :(得分:0)

试试此代码:REFERENCE

<?php
 $dates = array('2014-08', '2014-09', '2014-11', '2014-12', '2015-02');
 $begin = new DateTime( '2014-08' );
 $end = new DateTime( '2015-02' );
 $end = $end->modify( '+1month' ); 

 $interval = new DateInterval('P1M');
 $daterange = new DatePeriod($begin, $interval ,$end);

 foreach($daterange as $date){
  if(in_array($date->format("Y-m") , $dates)){
 echo $date->format("Y-m") . "Active"."<br>";
 }else{
 echo $date->format("Y-m") . "Inactive"."<br>";
 }
 }?>

答案 2 :(得分:0)