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
这一切都是正确的,在我计算了这个月的日子之后,我只是难以对数组进行求和。
答案 0 :(得分:0)
$tot = 0;
foreach ($months as $days) {
$tot += daysInMonths(days);
}
echo $tot;
答案 1 :(得分:0)
array_sum() - http://php.net/manual/en/function.array-sum.php
$t = array(
31,
28,
31
);
echo array_sum($t); // 90
答案 2 :(得分:0)
添加一个像你一样使用的计数器等等!!