2013-05-06 60 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

相關問題