【发布时间】:2017-01-13 04:20:31
【问题描述】:
我有一个小功能,可以抓取指定视频上评论作者的头像。它只是循环通过 YouTube API v3 commentThreads 方法返回的 JSON 数据。
唯一的问题是,有时作者不止一次发表评论,所以我的功能是多次显示作者头像。我只想显示一次,然后显示到下一个头像。
目前我的函数如下所示:
function videoCommentAvatars($video) {
// Parse YouTube video ID from the url
if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $video, $match)) {
$video_id = $match[1];
}
// Gather Video stats with YouTube API v3
$api_key = "API_KEY_HERE";
$JSON = file_get_contents('https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId='.$video_id.'&key='.$api_key);
$json_data = json_decode($JSON, true);
if (!empty($json_data)) {
foreach ($json_data['items'] as $data) {
// Create variables that hold info
$author_name = $data['snippet']['topLevelComment']['snippet']['authorDisplayName']; // Author Name
$author_avatar = $data['snippet']['topLevelComment']['snippet']['authorProfileImageUrl']; // Author Avatar
$author_channel = $data['snippet']['topLevelComment']['snippet']['authorChannelUrl']; // Author Channel URL
echo '<span class="comment-author-avatar">';
echo '<a target="_blank" href="'.$author_channel.'" title="'.$author_name.'"><img width="50" alt="'.$author_name.'" class="comment-author-thumb-single" src="'.$author_avatar.'"></a>';
echo '</span>';
}
}
}
一切正常,但无法检查头像是否已显示。我想过使用数组吗?将每个头像 URL 添加到数组中,并检查数组以查看键是否存在。但这对于看似更简单的事情来说似乎有点过头了。有没有人有一个聪明的方法来检查 foreach 循环是否有重复项?
【问题讨论】:
-
您的问题是否检查重复项?还是看头像有没有显示?
-
@CasparWylie 无论如何都可以确定头像是否已显示。我只想显示每个头像一次。我想最好看看它是否已显示,而不是事后检查是否有重复。谢谢!
-
为什么不显示?您正在从后端(php)输出数据/头像,因此您可以假设数组中的所有内容都是在页面加载时输出的,不是吗?
标签: php json foreach youtube duplicates