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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料