Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用php计算时间?_Php - Fatal编程技术网

如何用php计算时间?

如何用php计算时间?,php,Php,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)); $nu

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');
计数后:
0:30
1:31
2:31
3:29
4:31

这一切都是正确的,我只是在计算了一个月的天数之后,对数组求和遇到了问题。

array\u sum()

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

添加一个计数器,如您在中使用的while等

您的
calDaysInMonth()
函数可以替换为一个简单的
date('t',$date)
.Wow。那很容易。谢谢。也许你应该举个例子
$tot = 0;
foreach ($months as $days) {
    $tot += daysInMonths(days);
}
echo $tot;
$t = array(
    31,
    28,
    31
);

echo array_sum($t); // 90