2013-05-06 61 views
-4

如何从某个月份查找数组中的日期? 阵列结构是:如何查找数组中的日期?

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) 

我需要的功能,我给人以日期排列,一个月的数量,并与该月份的日期返回数组。

+6

向我们展示[你试过的东西](http://mattgemmell.com/2008/12/08/what-have-you-tried/)。请参阅[关于堆栈溢出](http://stackoverflow.com/about)。 – 2013-05-06 20:45:36

回答

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日

+1

请注意,这使用'explode'将日期分成年/月/日。如果您使用不同的格式,则需要更改。最好你应该使用的DateTime对象:php.net/datetime – 2013-05-06 20:54:02

+0

谢谢,这正是我需要的:) – LaKaede 2013-05-06 21:09:03

+0

我想拿到每月数最简单的方法是'$月=日期(“N”,的strtotime($日期) );'。 – 2013-05-06 21:21:22

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; 
} 
+0

+1,我其实是想strtotime'但'date_parse的' '非常酷。很好的补充。 – 2013-05-06 21:19:28

+0

我从来不知道'date_parse',真好! – 2013-05-07 12:17:32