从php数组中提取月份数据

时间:2011-01-09 09:47:57

标签: php

我有一个包含日期的数组我希望这个月的子集明智吗? 数组中的日期格式为$dates = array('2010-11-01',.....);

3 个答案:

答案 0 :(得分:1)

注意:它不仅支持您的日期格式,还支持许多其他日期格式。您还可以使用数字或字母表示的月份。

你可以循环它:

$arr = array( '2009-1-1', '2009-2-1','2009-3-1','2009-3-1' );

$output = array();

foreach( $arr as $date ){
   $output[date('m', strtotime($date))][] = $date; 
}

print_r($output);

Test It Here


<小时/> 您也可以使用月份名称:

$output[date('M', strtotime($date))][] = $date; 

Test It Here


<小时/> 对于年度月份,您可以这样做:

$output[date('y', strtotime($date))][date('m', strtotime($date))][] = $date;

Test It Here

答案 1 :(得分:1)

无需使用日期类。相反,我们可以使用substr()来获取YYYY-MM和索引。

$dates = array('2010-11-11', '2010-01-14', '2010-01-17', '2011-01-03');
$months = array();
foreach($dates as $date) {
  $month = substr($date, 0, 6);
  $months[$month][] = $date;
}
print_r($months);

Output

Array
(
    [2010-1] => Array
        (
            [0] => 2010-11-11
        )

    [2010-0] => Array
        (
            [0] => 2010-01-14
            [1] => 2010-01-17
        )

    [2011-0] => Array
        (
            [0] => 2011-01-03
        )

)

答案 2 :(得分:0)

我根本没有对此进行测试,但假设数组$ date由时间戳组成,则以下内容应该有效

$months = array();
foreach($dates as $date) {
$months[date('F', $date)][] = $date;
}