【问题标题】:how to show show active and inactive month from given date array如何显示给定日期数组中的活动和非活动月份
【发布时间】:2015-03-10 02:42:47
【问题描述】:

我需要一个 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

【问题讨论】:

  • 活跃或不活跃的条件是什么?
  • 活跃/不活跃基于哪些?

标签: php function date compare


【解决方案1】:

这应该适合你:

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

【讨论】:

    【解决方案2】:
    【解决方案3】:

    试试这个代码: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>";
     }
     }?>
    

    【讨论】:

    • 怎么可能你的所有输出都处于非活动状态,但在 OP 的预期输出中,他只有 2 个处于非活动状态?!
    • @Rizier123 是的,你是对的,但他没有提到活动/非活动背后的条件是什么,所以我把条件放在今天的日期(Y-m)。
    • 看问题就知道条件了!
    • @Rizier123 得到了条件,谢谢亲爱的。我会及时更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多