首页 文章

如何在PHP中总结时间?

提问于
浏览
0

PHP:如何总结foreach语句的结果?

以下是我的工作代码 . 正如您将看到的,我正在尝试计算每个月的日子然后总结它们 .

//  A function to calculate days in a given month using just the date
function daysInMonths($date)
{
    $month = date("m", strtotime($date));
    $year =  date("Y", strtotime($date)); 
    $num = cal_days_in_month(CAL_GREGORIAN, $month, $year); 
    return $num;
}       

// A function that places the date of an unknown number of months into an array:
function getNextMonths($date, $numberOfMonths)
{
    $timestamp_now = strtotime($date);
    $months[] = date('Y-m-d', $timestamp_now);

    for($i = 1;$i <= $numberOfMonths; $i++)
        {
            $months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
        }

// counts the days in each month:
    $j=0;
    foreach ($months as $days)
    {
        echo "$j:".daysInMonths($days)."<br>";
        ++$j;            
    }
    print_r($months);
}

getNextMonths('2011-11-1', '4');

当前输出:

Array ( 
    [0] => 2011-11-01 
    [1] => 2011-12-01 
    [2] => 2012-01-01 
    [3] => 2012-02-01 
    [4] => 2012-03-01 
)

计数后:
0:30
1:31
2:31
3:29
4:31

这一切都是正确的,我只是在计算了这个月的日期后才能对数组进行求和 .

3 回答

  • 0

    array_sum() - http://php.net/manual/en/function.array-sum.php

    $t = array(
        31,
        28,
        31
    );
    
    echo array_sum($t); // 90
    
  • 0

    添加一个像你一样使用的计数器等!

  • 0
    $tot = 0;
    foreach ($months as $days) {
        $tot += daysInMonths(days);
    }
    echo $tot;
    

相关问题