2016-02-05 91 views
0

我在Instagram API中做了些什麼,並且對函數循環有點困惑。php函數再次返回函數

我嘗試創建代碼以從instagram用戶獲取所有圖像,但API僅限制20張圖像。我們必須接下來的電話才能進入下一頁。

我對我的應用程序使用了https://github.com/cosenary/Instagram-PHP-API,這裏是獲取圖像的函數。

function getUserMedia($id = 'self', $limit = 0) 
{ 
    $params = array(); 

    if ($limit > 0) { 
     $params['count'] = $limit; 
    } 

    return $this->_makeCall('users/' . $id . '/media/recent', strlen($this->getAccessToken()), $params); 
} 

我試着撥打電話,返回值是

{ 

"pagination": 

{ 

"next_url": "https://api.instagram.com/v1/users/21537353/media/recent?access_token=xxxxxxx&max_id=1173734674550540529_21537353", 
"next_max_id": "1173734674550540529_21537353" 

}, [.... another result data ....] 

第一功能的結果,併產生20幅圖像。

我的問題是:

  1. 如何從傳回該功能,再次使用next_max_id參數的功能,所以它會循環,再次使用該功能?
  2. 如何將結果合併爲1個對象數組?

對不起,我的英語和我的解釋不好。

謝謝你的幫助。

+0

以這種方式修改你的函數:'getUserMedia($ id ='self',$ limit = 0,$ next_max_id = 0)' – fusion3k

回答

0

您應該使用遞歸函數 和停止功能,當next_url發現空/空

0

從Instagram的-PHP-API文檔,在我看來,你應該使用分頁()方法來獲得你的下一個頁面:

$photos = $instagram->getTagMedia('kitten'); 
$result = $instagram->pagination($photos); 

只需使用條件(如果),以驗證是否$結果有內容,如果有,撥打另一個電話與分頁()請求下一個頁面。以遞歸方式進行。

但我認爲這是不使用Instagram的-PHP-API while循環來實現一個不錯的主意:

$token = "<your-accces-token>"; 
$url = "https://api.instagram.com/v1/users/self/media/recent/?access_token=".$token; 

while ($url != null) { 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $output = curl_exec($ch); 
    curl_close($ch); 

    $photos = json_decode($output); 

    if ($photos->meta->code == 200) { 

     // do stuff with photos 

     $url = (isset($photos->pagination->next_url)) ? $photos->pagination->next_url : null; // verify if there's another page 

    } else {  
     $url = null; // if error, stop the loop 
    } 

    sleep(1000); // to avoid to much requests on Instagram at almost the same time and protect your rate limits API 
} 

祝你好運!