我是php新手,我想知道如何检索随机播放的YouTube ID .. 这就是我的意思..
$playlist_id = "PLB9DAD6B9EDAEE7BC";
$cont = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/'.$playlist_id.'/?v=2&alt=json&feature=plcp'));
$feed = $cont->feed->entry;
if(count($feed)) {
foreach($feed as $item) {
$title = $item->title->{'$t'};
$desc = $item->{'media$group'}->{'media$description'}->{'$t'};
$id = $item->{'media$group'}->{'yt$videoid'}->{'$t'};
}
}
这基本上从播放列表中获取id,title和description,如何将$id
随机播放给我独特的重复值,以便我以后可以在这里使用它?
<iframe ... src="http://www.youtube.com/embed/<?= $id ?>" allowfullscreen></iframe>
我的目标是每次访问时刷新页面以获取新视频,并在结束时自行重置(或者只是继续选择唯一值)
提前谢谢你,很多..
答案 0 :(得分:1)
您可以将所有Feed视频存储在一个数组中,然后使用array_rand获取该数组的随机条目。
有关功能参考,请参阅http://php.net/manual/de/function.array-rand.php。 请注意,当使用默认设置时,array_rand会返回单个键,但如果您选择多个单个随机条目,它将提供一个键数组。
编辑:添加了Cookie,因此视频是真实的随机唯一
代码段:
$playlist_id = "PLB9DAD6B9EDAEE7BC";
$cont = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/'.$playlist_id.'/?v=2&alt=json&feature=plcp'));
$feed = $cont->feed->entry;
$youtubeVideos = array();
if(count($feed))
{
foreach($feed as $item)
{
// build video array
$video = array();
$video['title'] = $item->title->{'$t'};
$video['desc'] = $item->{'media$group'}->{'media$description'}->{'$t'};
$video['id'] = $item->{'media$group'}->{'yt$videoid'}->{'$t'};
// push it into collection
$youtubeVideos[$video['id']] = $video;
}
}
$seenVideos=array();
$lastSeenVideo='';
// only get diff array if the cookies are set (= not first page view)
if(isset($_COOKIE['seen_youtube_videos']) && isset($_COOKIE['last_youtube_video']))
{
$lastSeenVideo=$_COOKIE['last_youtube_video'];
$seenVideos=unserialize($_COOKIE['seen_youtube_videos']);
$diffArr=$youtubeVideos;
foreach($seenVideos as $vidId)
unset($diffArr[$vidId]);
if(count($diffArr)>0)
{
// set difference for searching only
$youtubeVideos=$diffArr;
}
else
{
// if we did show all videos, reset everything
setcookie('seen_youtube_videos', '');
setcookie('last_youtube_video', '');
$seenVideos = array();
}
}
$randomizedKey = array_rand($youtubeVideos);
$randomVideo = $youtubeVideos[$randomizedKey];
do
{
$randomizedKey = array_rand($youtubeVideos);
$randomVideo = $youtubeVideos[$randomizedKey];
}
while($randomVideo['id'] == $lastSeenVideo);
$seenVideos[] = $randomVideo['id'];
setcookie('seen_youtube_videos', serialize($seenVideos));
setcookie('last_youtube_video', $randomVideo['id']);
// do stuff with $randomVideo