在PHP中操作日期数组

时间:2014-12-12 22:15:44

标签: php arrays date

我在PHP中接近一段代码时遇到了很多困难。我有一系列日期和值,例如

dates = (2014-12-01,2014-12-02,2014-12-08,2014-12-09,2014-12-10,2014-12-11)
values = (5,3,7,8,9,2)

您会注意到12/01是星期一,12/08也是如此。我想从这两个数组中形成4个数组:

monday = (5,7)
tuesday = (3,8)
wednesday = (0,9)
thursday = (0,2)

您会注意到,通过抓取与星期几相关的值来形成阵列。但是,例如,如果存在星期三的日期,但前一个星期二没有,则该数组应该为“0”。换句话说,4个数组应该都是相同的长度。

任何人都可以帮我用PHP编写代码来实现这一目标吗?提前谢谢!

注意:到目前为止,我只确定了如何从日期中找到星期几:date('l', strtotime("2014-12-08"));我真的无法找出解决此问题的一般算法。

2 个答案:

答案 0 :(得分:1)

$dates  = array( '2014-12-01','2014-12-02','2014-12-08','2014-12-09',
                 '2014-12-10','2014-12-11' );
$values = array( 5, 3, 7, 8, 9, 2 );

$date  = strtotime(min($dates));
$stop  = strtotime(max($dates));
$dates = array_flip($dates);
$out   = array();

while($date <= $stop)
{
   $tmp = date('Y-m-d', $date);
   $out[date('l', $date)][] = isset($dates[$tmp]) && isset($values[$dates[$tmp]]) ?
                              $values[$dates[$tmp]] : 0;  
   $date = strtotime('+1 day', $date);   
}

print_r($out);

结果:

Array
(
    [Monday] => Array
        (
            [0] => 5
            [1] => 7
        )

    [Tuesday] => Array
        (
            [0] => 3
            [1] => 8
        )

    [Wednesday] => Array
        (
            [0] => 0
            [1] => 9
        )

    [Thursday] => Array
        (
            [0] => 0
            [1] => 2
        )

    [Friday] => Array
        (
            [0] => 0
        )

    [Saturday] => Array
        (
            [0] => 0
        )

    [Sunday] => Array
        (
            [0] => 0
        )

)

ps:how can I get the an array of all the dates included in the "dates" array associated with only all the Mondays?

修改代码,例如:

   $tmp = date('Y-m-d', $date);
   $exists = isset($dates[$tmp]) && isset($values[$dates[$tmp]]);
   $out[date('l', $date)]['numbers'][] = $exists ? $values[$dates[$tmp]] : 0; 
   if ($exists) $out[date('l', $date)]['dates'][] = $tmp;
   $date = strtotime('+1 day', $date);  

你会得到一个输出(例如星期一)

[Monday] => Array
    (
        [numbers] => Array
            (
                [0] => 5
                [1] => 7
            )

        [dates] => Array
            (
                [0] => 2014-12-01
                [1] => 2014-12-08
            )

    )

答案 1 :(得分:0)

可能是一个更好的方法让0在那里没有另一个循环,但我走了出去:

foreach($dates as $key => $val) {
    $day = date('l', strtotime($val));
    $result[$day][] = $values[$key];
}
foreach($result as &$val) {
    if(count($val) == 1) {
        array_unshift($val, 0);
    }
}
print_r($result);