且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 21:46:54

这是典型的用法 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
)