2016-02-05 67 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 
} 

祝你好运!