【发布时间】:2015-08-25 17:47:33
【问题描述】:
守则
我创建了一个 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["photos"] 数组的末尾:
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,
"content-type" => "application/json"
)
)
);
try {
$response = json_decode( $body, 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 块正在创建一个闭包,我不确定该怎么做。
【问题讨论】:
-
$response数组的输出是什么 -
嗨@MichaelStClair,您可以在这里找到响应信封的结构:Instagram API Endpoints
-
打印出
$response["pagination"]["next_url"];,看看那里有没有值 -
@MichaelStClair 我也怀疑过,但它按预期从 json 中返回 pagination.next_url 参数。
-
你需要在它前面的
$this->来将该值分配给数组吗?如果删除它会发生什么?
标签: php wordpress oop pagination instagram