Youtube API - 从搜索(查询)中排除视频


Youtube API - exclude video from search (query)

我通过PHP客户端(类似于Google(https://developers.google.com/youtube/v3/code_samples/php#search_by_keyword)提供的基本代码)获得使用Ajax的视频列表。

它工作正常,但是现在,我想从对API的查询中排除一些视频:由于我可以检索(例如)50个结果,因此我需要获得50个结果,不包括我已经拥有的一些视频ID

目前,我在客户端(使用 JS)检查它,但正如您所料,我得到了 50(- 我用 JS 排除的视频数量)结果......

我对 API 的 PHP 调用:

$searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['query'],
  'maxResults' => $_GET['maxNb'],
));

是否有一个参数,我可以在其中放置要排除的视频 ID 数组?

您想排除某些视频,但您仍然希望获得相同数量的结果,据我所知,Youtube API 中没有用于排除某些视频的参数,但您可以使用 PHP 排除它们。

例如

// unwanted videos 
$excludedVideos = ['h2Nq0qv0K8M','_jKylhJtPmI','55GkIZOCeM8','_A3I9RDR6GA'];

现在您应该获得视频+排除的视频数量

 $searchResponse = $youtube->search->listSearch('id,snippet', array(
  'q' => $_GET['q'],
  // get your results + the number of unwanted videos
  'maxResults' => $_GET['maxResults'] + count($excludedVideos),
));

从结果中删除不需要的视频

 // remove unwanted videos
foreach($searchResponse['items'] as $key => $item){
     if(in_array($item->id->videoId, $excludedVideos)){
          unset($searchResponse[$key]);
     }
}

现在是时候显示结果了,您无法保证所有$excludedVideos数都会显示在结果中,因此您需要将结果限制为$_GET['maxResults']

 $limit = 1;
 foreach ($searchResponse['items'] as $searchResult) {
      if($limit == $_GET['maxResults']) break;
      // do what ever you want with the results here
      $limit++; 
 }

这只是一个给你一个想法的例子,你可以根据你的要求改变代码。