如何在数组中查找日期?

时间:2013-05-06 20:44:50

标签: php arrays date find

如何从某个月开始查找数组中的日期? 数组结构是:

Array ( [0] => 2013-05-23 
        [1] => 2013-05-24 
        [2] => 2013-05-25 
        [3] => 2013-05-26 
        [4] => 2013-05-27 
        [5] => 2013-06-02 
        [6] => 2013-06-03 
        [7] => 2013-06-04 )

我需要函数,我给数组添加日期,月份数,然后返回包含该月日期的数组。

2 个答案:

答案 0 :(得分:2)

我会使用date_parse内置函数返回日期数组

$dates = array(
    0 => '2013-05-23', 
    1 => '2013-05-24',
    2 => '2013-05-25',
    3 => '2013-05-26', 
    4 => '2013-05-27', 
    5 => '2013-06-02', 
    6 => '2013-06-03', 
    7 => '2013-06-04'

);

$date = getDate(05, $dates);

function getDate($month, $dates){
    $return = array();
    foreach($dates as $date){
    $check = date_parse($date);
        if($check['month'] == $month){
            array_push($return, $date);
        }
    }
return $return;
}

答案 1 :(得分:1)

function narrowByMonth($dates, $monthNumber) {
    foreach ($dates as $date) {
        $split = explode('-', $date);
        $year = $split[0]; // Not needed in this example
        $month = $split[1];
        $day = $split[2]; // Not needed in this example
        if ($month == $monthNumber) {
            echo $date.'<br />';
        }
    }
}

$dates = array ('2013-05-25',
    '2013-05-26',
    '2013-06-02',
    '2013-06-03');

$monthNumber = '05';

narrowByMonth($dates, $monthNumber);

输出:

2013年5月25日
2013年5月26日