2015-01-13 22 views
-2

我做了一個解析網站某個頁面(論壇帖子)的函數。它應該選擇用戶和他們的帖子,然後進入下一頁並執行相同的操作。雖然這樣做,但其返回值始終爲空。我認爲我在遞歸方面犯了一個錯誤,但無法真正弄明白。遞歸解析函數

這裏是函數,我現在只讓它返回用戶列表。

function getWinners($thread,$userlist,$postlist) { 
    //libxml_use_internal_errors(true); 
    $html = file_get_html($thread); 


    //get users 
    $users=$html->find('li[class="postbitlegacy postbitim postcontainer old"] div[class=username_container] strong span'); 
    foreach ($users as $user) 
     //echo $user . '<br>'; 
     array_push($userlist, $user); 
    //get posts 
    $posts=$html->find('li[class="postbitlegacy postbitim postcontainer old"] div[class=postbody] div[class=content]'); 
    foreach ($posts as $post) 
     // echo $post . '<br>'; 
     array_push($postlist, $post); 
    //check if there is a next page 
    if ($next=$html->find('span[class=prev_next] a[rel="next"]', 0)) { 
     $testa='http://forums.heroesofnewerth.com/'.$next->href; 
     // echo $testa. '<br>'; 
     $html->clear(); 
     unset($html); 

     //recursive calls until the last page of the forum thread 
     getWinners($testa,$userlist,$postlist); 

    //no more thread, return users 
    }else return $userlist; 
} 

和呼叫

$thread='http://forums.heroesofnewerth.com/showthread.php?553261'; 

    $userlist=array(); 
    $postlist=array(); 

$stuff=getWinners($thread,$userlist,$postlist); 
echo $stuff[0]; 

這裏,東西是空的。

+0

完成任何基本的調試,如echoi排除你正在建設的網站,看看它們是否合法? –

+0

你確定要返回'$ users'而不是'$ userlist'嗎? – mopo922

+0

是的,他們工作。該函數遍歷頁面並收集用戶和帖子,將它們添加到數組中,但其返回值爲空。 –

回答

1

至少,你需要使用來自遞歸函數的返回值:

getWinners($testa,$userlist,$postlist); 

應該是:

return getWinners($testa,$userlist,$postlist); 
// or, more likely: 
return array_merge($users, getWinners($testa,$userlist,$postlist)); 

除此之外,我不知道,如果你正在返回正確的信息,可能(你需要檢查...)你需要類似的東西:

//cursive calls until the last page of the forum thread 
    return array_merge($userlist, getWinners($testa,$userlist,$postlist)); 
} 
else { 
    //no more thread, return users 
    return $userlist; 
} 
+1

我發現了這個問題。 $ HTML的「清晰();正在刪除所有以前的值。不過,我會接受你的回答,因爲它提供了有關遞歸的很好的提示。謝謝你。 –