2017-05-16 46 views
-2

這裏是我的PHP代碼,測試方法不給想要的輸出,另一個奇怪的事情是var_dump('a')打印3次;我的PHP代碼與遞歸方法有什麼問題?

我想要的輸出是數組('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; 
} 
+0

爲什麼你傳遞$ imgArray測試? – VK321

+2

爲什麼你需要一個遞歸函數?你想做什麼?你可以取每個元素並在該字符串前加上。 – cornelb

+1

'test()'函數被調用3次,這就是爲什麼你得到三個「a」。這裏的問題是邏輯。 –

回答

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

謝謝,它有幫助!並感謝大家。 – kuzicala

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

這些代碼是簡單的演示,我不認爲foreach可以得到我想要的,因爲真實場景是我需要從其他平臺下載一些圖像,如果互聯網擁擠,結果不會返回,但是foreach仍在運行。 – kuzicala

+0

當我使用forEach的javascript將一些圖像上傳到第三方平臺時,forEach運行完成,但結果未定義, – kuzicala