dourang8305
2017-05-16 13:03
浏览 6
已采纳

使用递归方法我的PHP代码有什么问题?

Here is my php code, the test method not giving wanted output, and the other weird thing is var_dump('a') print 3 times;

my wanted output is array('qtggccc','qtff23sdf');

public function main()
{
    $serverIds = array('ff23sdf','ggccc');
   $res =  $this->test($serverIds);
    var_dump($res);
}

public function  test($serverIds,$imgArray = array())
{
    if(count($serverIds) > 0){
        $media_id = array_pop($serverIds);
        $imgUrl= $this->hh($media_id);
        array_push($imgArray,$imgUrl);
        var_dump($serverIds);
        var_dump($imgArray);
        $this->test($serverIds,$imgArray);
    }
    var_dump('a');
    return $imgArray;
}

public function hh($m)
{
    return 'qt'.$m;
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dshkmamau65777662 2017-05-16 13:30
    已采纳

    Try this:

    class MyClass{
    
       private $imgArray = array();
    
       public function main(){
    
         $serverIds = array('ff23sdf','ggccc');
         $res =  $this->test($serverIds);
         print_r($this->imgArray);
       }
    
      public function  test($serverIds){
    
       if(count($serverIds) > 0){
           $media_id = end($serverIds);
           $imgUrl= $this->hh($media_id);
           array_push($this->imgArray,$imgUrl);
           //remove last element
           array_pop($serverIds);
           $this->test($serverIds);
       }
      return;
     }
    
      public function hh($m){
        return 'qt'.$m;
      }
    }
    
    $obj = new MyClass();
    echo '<pre>';
    $obj->main();
    
    打赏 评论
  • duanbei1709 2017-05-16 13:28

    Why use recursion? You are using a complicated solution for a simple problem.

    public function main()
    {
        $serverIds = array('ff23sdf','ggccc');
        $res = array();
    
        //These three lines replace an entire recursive function, making the code easier and saving a chunk of memory once you start using real arrays
        foreach ($serverIds as $media_id){
            array_unshift($res, $this->hh($media_id));
        }
        var_dump($res);
    }
    
    public function hh($m)
    {
        return 'qt'.$m;
    }
    
    打赏 评论

相关推荐 更多相似问题