使用不同的函数调用查找累积和

时间:2016-03-07 07:27:07

标签: php

我试图从SQL查询中获取'count'的累积总和,该查询是从具有不同参数的函数getCumChartStatusesByWeek调用的。 但变量cumulativeSum显示错误为'Undefined variable',仅显示实际计数,而不是累计总和。

对我做错了什么的想法?

$jsonDataCumArray = [];
$cumulativeSum = 0;

$jsonDataCumArray[] = getCumChartStatusesByWeek($statusID, $wwAreaMinus1, $wwAreaNow);
$jsonDataCumArray[] = getCumChartStatusesByWeek($statusID, $wwAreaNow, $wwAreaPlus1);
$jsonDataCumArray[] = getCumChartStatusesByWeek($statusID, $wwAreaPlus1, $wwAreaPlus2);
$jsonDataCumArray[] = getCumChartStatusesByWeek($statusID, $wwAreaPlus2, $wwAreaPlus3);

//Quick function used to grab data for the above bar graph

function getCumChartStatusesByWeek($statusID,$startTime1, $endTime1){
 global $db,$AndCustomersInString;
 $jsonCumData = [];
 $qCum =   "SELECT COUNT(*) as count 
         FROM request_meta rmm
         LEFT JOIN request_taxonomy rtt ON rtt.id = rmm.id
         WHERE rtt.req_a_id = $statusID
         AND rmm.req_id IN
             (SELECT r.req_id FROM requests r 
              WHERE UNIX_TIMESTAMP(STR_TO_DATE(r.date_created,'%Y-%m-%e %H:%i:%s')) BETWEEN $startTime1 AND $endTime1                  
              $AndCustomersInString
             )
             AND rmm.meta_value='New' ";

         $row1 = $db->query($qCum)->fetchAll();
         $cumulativeSum +=  $row1['count'];
         $jsonCumData['NewRequests'] = $cumulativeSum;

      return $jsonCumData;
}

结果

    json
Array
(
    [y] => 2016-02-15
    [NewRequests] => 2
)
json
Array
(
    [y] => 2016-02-22
    [NewRequests] => 9
)
json
Array
(
    [y] => 2016-02-29
    [NewRequests] => 2
)
json
Array
(
    [y] => 2016-03-07
    [NewRequests] => 0
)

1 个答案:

答案 0 :(得分:1)

错误是因为$cumulativeSum 超出了函数的范围

制作$cumulativeSum global或将其作为function传递给argument

global $db,$AndCustomersInString, $cumulativeSum;

或者

$jsonDataCumArray[] = getCumChartStatusesByWeek($statusID, $wwAreaMinus1, $wwAreaNow, $cumulativeSum);

并且

function getCumChartStatusesByWeek($statusID,$startTime1, $endTime1, $cumulativeSum){
   .....
}