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

时间:2017-05-16 13:03:07

标签: php

这是我的PHP代码,测试方法没有给出想要的输出,另一个奇怪的事情是var_dump(' a')打印3次;

我想要的输出是数组(' 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 个答案:

答案 0 :(得分:0)

为什么要使用递归?您正在使用复杂的解决方案解决一个简单的问题。

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

答案 1 :(得分:0)

试试这个:

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();