Removing expired dates from an array with PHP

随声附和 提交于 2020-11-29 10:34:59

问题


I have an array of dates formatted in 'm/d/Y' (month/day/year):

$array = array(

'1/10/2014',
'1/11/2014',
'1/12/2014',
'1/13/2014',
'1/14/2014'
);

and I'd like to output the array with only dates of today or in the future. So if today is 1/12/2014 it would eliminate the 1/10/2014 and 1/11/2014.

Here is what I have that isn't working:

foreach ($array as $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

 unset($array[$date]);

 }

}

print_r($array);

I guess I'm not using unset correctly because it prints the entire array?


回答1:


I suggest you look into array_filter(). Also you want to use today's date at 12:00:00 for the comparisson, not the current time.

$array = array(
    '1/10/2014',
    '1/11/2014',
    '1/12/2014',
    '1/13/2014',
    '1/14/2014'
);

$array = array_filter($array,function($date){
    return strtotime($date) >= strtotime('today');
});

print_r($array); //Array ( [2] => 1/12/2014 [3] => 1/13/2014 [4] => 1/14/2014 )

*Note: PHP 5.3 needed for anonymous functions




回答2:


Try

foreach ($array as $key => $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

 unset($array[$key]);

 }

}

print_r($array);



回答3:


foreach ($array as &$date) Hi using call by reference and $date = NULL; in the loop

OR

foreach ($array AS $key => $date) {

 $unixdate = strtotime($date);

 if ($unixdate < time()) {

    unset($array[$key]);

 }

}

if you want to completely remove those entries



来源:https://stackoverflow.com/questions/21079595/removing-expired-dates-from-an-array-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!