递归循环转为while循环
1:对youtube的分页数据,递归调用,以获取所有数据:
/** * getVideoIds 从youtube获取videoids * @date 2021-05-22 19:43 * @param YoutubeRepositoryInterface $youtubeRepository * @param $oauth * @param $params * @param int $video_count * @return array */ private function getVideoIds(YoutubeRepositoryInterface $youtubeRepository,$oauth,$params,$video_count=0) { $videoIdsArr = []; static $number = 0; $method = $params['method']; $itemsResponse = $youtubeRepository->$method($oauth,$params['part'],$params['params']); if ($itemsResponse && isset($itemsResponse->items)) { foreach($itemsResponse->items as $video) { $snippet = $video->snippet; if ($params['source_type_channel']) { $videoId = $video->id->videoId; } else { $videoId = $snippet->resourceId->videoId; if ($this->start_time && $this->start_time) { $publish_at = Carbon::parse($snippet->publishedAt)->timestamp; if ($publish_at > $this->end_time || $publish_at < $this->start_time) { continue; } } } $videoIdsArr[] = $videoId; $number = $number + 1; if ($video_count && ($number >= $video_count)) { $number = 0; break; } } } // 循环获取分页的数据 if ($number && $itemsResponse && $itemsResponse->nextPageToken) { $params['params']['pageToken'] = $itemsResponse->nextPageToken; $videoIdsArr = array_merge($videoIdsArr,$this->getVideoIds($youtubeRepository,$oauth,$params,$video_count)); } else { unset($params['params']['pageToken']); $number = 0; } return $videoIdsArr; }
2:将上面的递归循环转换为while循环
/** * getVideoIds 从youtube获取videoids * @date 2021-05-22 19:43 * @param YoutubeRepositoryInterface $youtubeRepository * @param $oauth * @param $params * @param int $video_count * @return array */ private function getVideoIds(YoutubeRepositoryInterface $youtubeRepository,$oauth,$params,$video_count=0) { $videoIdsArr = []; $number = 0; $flag = true; $method = $params['method']; // 循环获取分页的数据 while ($flag) { $itemsResponse = $youtubeRepository->$method($oauth,$params['part'],$params['params']); if ($itemsResponse && isset($itemsResponse->items)) { foreach($itemsResponse->items as $video) { $snippet = $video->snippet; if ($params['source_type_channel']) { $videoId = $video->id->videoId; } else { $videoId = $snippet->resourceId->videoId; } $videoIdsArr[] = $videoId; $number = $number + 1; if ($video_count && ($number >= $video_count)) { $number = 0; break; } } } if ($number && $itemsResponse && $itemsResponse->nextPageToken) { $params['params']['pageToken'] = $itemsResponse->nextPageToken; $flag = true; } else { unset($params['params']['pageToken']); $flag = false; } } return $videoIdsArr; }
3:转换成do while循环:
// 循环获取分页的数据 do { $res = $youtubeRepository->listSearch(null, 'snippet', $params); if ($res) { foreach ($res->items as $item) { $videos[] = [ $item->id->videoId, $item->snippet->publishedAt, $item->snippet->title, ]; } if ($res->nextPageToken) { $params['pageToken'] = $res->nextPageToken; } } else { $this->error('listSearch failed'); $this->error(print_r($params, true)); break; } } while ($res->nextPageToken);