簡體   English   中英

從遞歸函數返回數組

[英]return an array from a recursive function

我想我需要有關遞歸性的一些解釋...我在論壇上也看過一些相同的問題,但是對我沒有太大幫助。

這是我的功能:

public function tas ($nb_gift, array $winners)
{
    if ( !empty( $nb_gift ) ){
        $id_winner = rand( 10, 15 );
        if ( !$this->_in_array_r($id_winner, $winners) ){
            $existing_user = $this->getWinner( $id_winner );    
        }
        if( !empty( $existing_user ) && $nb_gift > 0 ){
            $winners[] = array( $existing_user, 'iphone5');
            $this->tas($nb_gift - 1, $winners);
        }
        else {
            if($nb_gift > 0)
            {
                $this->tas($nb_gift, $winners);
            }
        }
    } 
    else {
        //print_r($winners);
        return $winners;
    }
}

最后,我有一個由獲獎者組成的數組。 即使print_r有效,返回也不會給我返回數組。 函數是否需要一些優化?

您永遠不會從第一個if分支返回任何內容。 如果最初調用tas()並進入第一個if分支,則它永遠不會return s,因此調用方永遠不會收回任何東西。

實際上,遞歸沒有什么特別的。 您調用一個函數,您會得到一個結果:

$winners = tas();

簡單。 在內部,該函數可以調用其他函數:

function tas() {
    return foo();
}

tas不能自稱,但仍受返回數據的相同規則約束:

function tas() {
    if (...) {
        foo(); // <-- doesn't return anything
    } else {
        return foo();
    }
}

只需在上面的示例中用tas()代替foo()表示相同的概念,但包括遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM