Wings2fly
Wings2fly

Reputation: 927

Finding the cumulative sum with different function call

I am trying to get the cumulative sum of the 'count' from the SQL query , which is called from function getCumChartStatusesByWeek with different parameters. But the variable cumulativeSum is showing error as 'Undefined variable', and only the actual count is displayed, not the cumulative sum.

Any idea on what I am doing wrong?

$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;
}

Result

    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
)

Upvotes: 1

Views: 59

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31749

The error is because $cumulativeSum is out of scope of the function.

Either make $cumulativeSum global or pass it to the function as argument.

global $db,$AndCustomersInString, $cumulativeSum;

Or

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

And

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

Upvotes: 1

Related Questions