douxishai8552 2016-03-11 23:25
浏览 298
已采纳

PHP从数组中删除满足特定条件的值

So, long story short, I have an array of date objects ($occupied).

I want to compare these dates to a $now=dateTime() so that any $occupied[$i] that happens before $now will get removed. I have tried some solution with unset, another one with (a brand new) array_push(). Neither of it has worked, so i guess i am missing some logic apart from the obvious.. Any approach is welcome :) Here is interesting part of the code:

$occupied=["2016-02-19", "2016-02-20", "2016-02-21", "2016-02-18", "2016-02-19", "2016-02-20", "2016-02-21", "2016-03-30", "2016-03-25", "2016-03-26"].
$now = new DateTime();

my ideas included:

$now= new dateTime();
for($i=0;$i<count($occupied);$i++){
    $occupied[$i]=new dateTime($occupied[$i]);  
    $diff[$i] = $now->diff($occupied[$i]);
    echo $diff[$i]->format('%r%a');
    if(get_object_vars($diff[$i])["invert"]==1){
       unset($occupied[$i]);
      }
  }

and variations over the theme.. Apologize if it is trivial, my background is very basic... I have tried to avoid posting by reading PHP manual and some answers here featuring "remove values from array//remove elements by key" but I could not figure it out..

Thanks in advance!

  • 写回答

5条回答 默认 最新

  • douzhuanqian8244 2016-03-11 23:38
    关注

    This is a classic usage for array_filter(). And by the way, you can compare two DateTime objects directly, using the usual comparison operators. As long as they use the same timezone, PHP will produce the result you expect. (It produces correct results even if they don't use the same timezone, just that it's not as easy to compute them yourself without pen and paper when the timezones differ.)

    Now, the code:

    $occupied=["2016-02-19", "2016-02-20", "2016-02-21", "2016-02-18", "2016-02-19", "2016-02-20", "2016-02-21", "2016-03-30", "2016-03-25", "2016-03-26"];
    $now = new DateTime();
    
    $filtered = array_filter(
        $occupied,
        function ($date) use ($now) {
            // Keep only the items that are greater (later) than $now
            return $now <= new DateTime($date);
        }
    );
    
    print_r($filtered);
    

    It displays (today is 2016-03-12):

    Array
    (
        [7] => 2016-03-30
        [8] => 2016-03-25
        [9] => 2016-03-26
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?