我正在尝试显示来自YouTube的多个视频,而我正在使用YouTube API提取信息。
我有一切正常工作,除了,我想要查看viewCount的视频,其中最高的数字是第一个。
我可以简单地将其转换为数据库系统,但之后我必须运行一个cron作业(不是问题,只是试图避免额外需要运行超过需要的代码。)
$video = array(
"id1",
"id2",
"id3",
);
foreach ($video as $key) {
$api = "http://gdata.youtube.com/feeds/api/videos/$key?v=2&alt=json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$yt = json_decode(curl_exec($ch));
curl_close($ch);
$title = $yt->{'entry'}->{'title'}->{'$t'};
$viewCount = $yt->{'entry'}->{'yt$statistics'}->{'viewCount'};
$length = $yt->{'entry'}->{'media$group'}->{'yt$duration'}->{'seconds'};
$numDislikes = $yt->{'entry'}->{'yt$rating'}->{'numDislikes'};
$numLikes = $yt->{'entry'}->{'yt$rating'}->{'numLikes'};
$average = $yt->{'entry'}->{'gd$rating'}->{'average'};
$minutes = sprintf("%0.2f", $length / 60);
$seconds = str_replace(".", ":", $minutes);
//What I've tried, doesn't work. With and without if statement and max (Shouldn't need both, but I need the if statement to display one format of the number is higher) but too avail it hasn't successfully worked.
$views = 0;
foreach ($viewCount as $maxViews) {
$views = max($views,$maxViews);
if ($maxViews > $views) {
echo $views;
} else {
echo $viewCount;
}
}
}
这应该很简单,显然完全可以查看它,认为这是因为数组值不是数字,数字是从$ viewCount变量的每个foreach循环中提取的。
希望有人可以帮助我并正确修复此问题。
注意:我自己编写了此代码,但由于它是YouTube API,因此您可以自行使用该代码。 JSON解析有时会很麻烦。特别是使用YouTube的API。
此致