dongxi5423
2017-10-13 18:00
浏览 42
已采纳

递归函数不附加到数组

I've got a function that generates a matrix of date pairs. specifically, it takes two dates and adds the 31 day ranges to an array, so roughly, it would look like: [[date, date+31], [date, date+31], ...]

I'm using a recursive function to do it:

public function getBatchDates(Carbon $start, Carbon $end, array $arr) {
        $setEnd = Carbon::createFromTimestamp($start->getTimestamp())->addDays(31);
        if($setEnd->greaterThanOrEqualTo($end)) {
            $setEnd = $end;
            array_push($arr, array($start, $setEnd));
            return;
        }

        array_push($arr, array($start, $setEnd));

        $this->getBatchDates($setEnd, $end, $arr);
}

Now, when I debug the test that calls this function, it seems to work correctly:

look right

However, the test, which is roughly as follows:

$array = array();
getBatchDates(new Carbon("first day of December 2015"),Carbon::now(), $array);

$this->assertNotNull($array);
$this->assertGreaterThan(0, sizeof($array));

It fails, because the $array is 0-length. Is there something I'm missing, the debugger makes it look like things are working.

图片转代码服务由CSDN问答提供 功能建议

我有一个生成日期对矩阵的函数。 具体来说,它需要两个日期并将31天范围添加到数组中,所以粗略地看起来像: [[date,date + 31],[date,date + 31],...]

我正在使用递归函数来执行此操作:

  public function getBatchDates(Carbon $ start,Carbon $ end,  array $ arr){
 $ setEnd = Carbon :: createFromTimestamp($ start-> getTimestamp()) - > addDays(31); 
 if($ setEnd-> greaterThanOrEqualTo($ end)){
  $ setEnd = $ end; 
 array_push($ arr,array($ start,$ setEnd)); 
 return; 
} 
 
 array_push($ arr,array($ start,$ setEnd)); \  n 
 $ this-> getBatchDates($ setEnd,$ end,$ arr); 
} 
   
 
 

现在,当我调试调用此函数的测试时 功能,似乎工作正常:

然而,测试大致如下 :

 <鳕鱼 e> $ array = array(); 
getBatchDates(new Carbon(“2015年12月的第一天”),Carbon :: now(),$ array); 
 
 $ this-&gt; assertNotNull($ array);  
 $ this-&gt; assertGreaterThan(0,sizeof($ array)); 
   
 
 

失败,因为 $ array 是 长度为0的。 是否有一些我缺少的东西,调试器使它看起来像是有效的。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douyi3307 2017-10-13 18:02
    最佳回答

    Arrays in PHP are not passed into functions by reference, but by value. You'll need to either change the function signature to public function getBatchDates(Carbon $start, Carbon $end, array &$arr) (I think) or return the modified array.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题