代码
我创建了一个PHP类与Instagram的API进行通信.我正在使用一个名为api_request的私有函数(如下所示)与Instagram的API进行通信:
private function api_request( $request = null ) { if ( is_null( $request ) ) { $request = $this->request["httpRequest"]; } $body = wp_remote_retrieve_body( wp_remote_get( $request,array( "timeout" => 10,"content-type" => "application/json" ) ) ); try { $response = json_decode( $body,true ); $this->data["pagination"] = $response["pagination"]["next_url"]; $this->data["response"] = $response["data"]; $this->setup_data( $this->data ); } catch ( Exception $ex ) { $this->data = null; } }
这两行代码…
$this->data["pagination"] = $response["pagination"]["next_url"]; $this->data["response"] = $response["data"];
…在这个数组中设置我的数据:
private $data = array ( "response" => null,"pagination" => null,"photos" => array() );
问题
public function pagination_query() { $this->api_request( $this->data["pagination"] ); $output = json_encode( $this->data["photos"] ); return $output; }
Instagram给了我第一页,一遍又一遍的收获.
任何想法这里有什么问题?
更新#1
我意识到,因为我的setup_data函数(在api_request函数中使用)将我的照片对象推送到我的$this-> data [“照片”]数组的末尾:
private function setup_data( $data ) { foreach ( $data["response"] as $obj ) { /* code that parses the api,goes here */ /* pushes new object onto photo stack */ array_push( $this->data["photos"],$new_obj ); } }
…在请求新页面时需要创建一个空数组:
public function pagination_query() { $this->data["photos"] = array(); // kicks out old photo objects $this->api_request( $this->data["pagination"] ); $output = json_encode( $this->data["photos"] ); return $output; }
我可以检索第二页,但所有后续的pagination_query调用只返回第二页.任何想法可能是错的?
更新#2
我发现使用while语句,使api_request函数调用自身,允许我检索页面后页面很好:
private function api_request( $request = null ) { if ( is_null( $request ) ) { $request = $this->request["httpRequest"]; } $body = wp_remote_retrieve_body( wp_remote_get( $request,array( "timeout" => 18,true ); $this->data["response"] = $response["data"]; $this->data["next_page"] = $response["pagination"]["next_url"]; $this->setup_data( $this->data ); // while state returns page after page just fine while ( count( $this->data["photos"] ) < 80 ) { $this-> api_request( $this->data["next_page"] ); } } catch ( Exception $ex ) { $this->data = null; } }
但是,这并不能修复我的pagination_query函数,而且似乎我的try-catch块正在创建一个闭包,而且我并不确定该做什么.
在你的第一段代码中:
原文链接:https://www.f2er.com/php/139583.html$this->data["response"] = $response["data"]; $this->data["next_page"] = $response["pagination"]["next_url"];
注意两个键:响应和next_page
然后在你的第二个片段你有:
$this->data["pagination"] = $response["pagination"]["next_url"]; $this->data["response"] = $response["data"];
现在next_page是分页
现在,如果你使用
$this->api_request( $this->data["pagination"] );
但是你正在使用$this-> data [“next_page”] = $response [“pagination”] [“next_url”];当然你不会得到正确的结果.
在任何情况下,尝试var_dump您的$请求的内容:
public function pagination_query() { var_dump($this->data["pagination"]); $this->api_request( $this->data["pagination"] ); $output = json_encode( $this->data["photos"] ); return $output; }
如果你有一个debbugger也检查api_request里面是每次传递的url