PHP从数组中删除满足特定条件的值 [英] PHP removing values meeting specific conditon from array

查看:488
本文介绍了PHP从数组中删除满足特定条件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我有一系列日期对象(已占用)。

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

我想将这些日期与 $ now =进行比较dateTime(),以便删除在 $ now 之前发生的所有 $ occupied [$ i] 。我尝试了一些未设置的解决方案,另一个是使用(全新的)array_push()的解决方案。
都没有起作用,所以我想我除了明显的东西之外还缺少一些逻辑。.
任何方法都欢迎:)
这是代码中有趣的部分:

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();

我的想法包括:

$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]);
      }
  }

以及主题上的变化。.
抱歉,这很琐碎,我的背景很基础...我试图通过阅读PHP手册和此处的某些答案来避免通过键删除数组中的值//删除键中的值来避免发布内容,但我无法弄清楚。

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

预先感谢!

推荐答案

这是典型的用法 array_filter() 。顺便说一句,您可以比较两个 DateTime 对象,使用常规的比较运算符。只要他们使用相同的时区,PHP就会产生您期望的结果。 (即使它们不使用相同的时区,它也会产生正确的结果,只是当时区不同时,不用笔和纸自己计算它们不是那么容易。)

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.)

现在,代码:

$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);

显示(今天是 2016-03-12 ):

Array
(
    [7] => 2016-03-30
    [8] => 2016-03-25
    [9] => 2016-03-26
)

这篇关于PHP从数组中删除满足特定条件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆