Laravel控制器:PHP函数仅适用于第一次

时间:2018-02-09 06:49:11

标签: php laravel function

我在laravel的控制器中编写了一个私有函数用于一般用法,主要目的是返回某种类型数据的每日数据分布,例如每天的用户增长。

/* order Data into the form of data[date] = total data in the specific date */
private function dailyDataProcess($start, $end, $inputData, $timeStandard){

    if(!isset($processedData)){
        $processedData = array();
    }

    $numberOfData = $inputData -> count();

    $lengthOfTime = $end->diffInDays($start);

    $date = $end;

    for($i = 0; $i < $lengthOfTime; $i++){
        $dateString = $date->format('Y-m-d');
        if(!isset($processedData[$dateString])){
            $processedData[ $dateString ] = 0;
        }
        $date->subDay();
    }

    return $processedData;


    foreach($inputData as $data){

        //$timestandard depends on different datasets
        $date = new Carbon($data->$timeStandard); 
        $dateString = $date->format('Y-m-d');
        $processedData[$dateString] =  $processedData[$dateString] + 1;
    }

    return $this->array(['count' => $numberOfData, 'dailyData' => 
    $processedData]);


}

我连续五次调用此函数以获得不同的分布,但是当我进行单元测试时,该函数似乎在第一次成功运行。输出是

[{"2018-02-05":0,"2018-02-04":0,"2018-02-03":0,"2018-02-02":0,"2018-02-01":0,"2018-01-31":0,"2018-01-30":0,"2018-01-29":0,"2018-01-28":0,"2018-01-27":0,"2018-01-26":0,"2018-01-25":0,"2018-01-24":0,"2018-01-23":0,"2018-01-22":0,"2018-01-21":0,"2018-01-20":0,"2018-01-19":0,"2018-01-18":0,"2018-01-17":0,"2018-01-16":0,"2018-01-15":0,"2018-01-14":0,"2018-01-13":0,"2018-01-12":0,"2018-01-11":0,"2018-01-10":0,"2018-01-09":0,"2018-01-08":0},[],[],[],[]]

我不知道为什么会这样,功能似乎很好。因为它第一次运作良好。如果我注释掉这个函数的第一次调用,第一次调用是评论之前的第二次调用,该函数也可以正常工作。

2 个答案:

答案 0 :(得分:0)

函数中间的return语句停止进一步执行。

for($i = 0; $i < $lengthOfTime; $i++){
    $dateString = $date->format('Y-m-d');
    if(!isset($processedData[$dateString])){
        $processedData[ $dateString ] = 0;
    }
    $date->subDay();
}

// this needs to be refactored or removed entirely
return $processedData;

答案 1 :(得分:0)

终于找到了问题所在,

这一行改变了我在函数

中输入的原始Carbon对象
$date = $end;

并在此行的循环结束后

$date->subDay();

我的碳物已完全改变

所以现在我克隆了对象

$date = $end->copy();