【问题标题】:php function pass return to the function againphp function pass 再次返回函数
【发布时间】:2016-02-07 02:16:06
【问题描述】:

我正在使用 instagram API,对函数中的循环有点困惑。

我尝试创建代码以获取来自 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个对象数组?

如果我的英语不好,我的解释很抱歉。

感谢您的帮助。

【问题讨论】:

  • 这样修改你的函数:getUserMedia($id = 'self', $limit = 0, $next_max_id=0)

标签: php function api loops instagram


【解决方案1】:

你应该使用递归函数 并在 next_url 发现 null/empty 时停止该函数

【讨论】:

    【解决方案2】:

    从 Instagram-PHP-Api 文档看来,您应该使用 pagination() 方法来接收您的下一页:

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

    只需使用条件 (if) 来验证 $result 是否有内容,如果有,则使用 pagination() 再次调用以请求下一页。递归执行。

    但我认为在没有 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
    }
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      相关资源
      最近更新 更多