所以我正在使用Googles YouTube API,我希望返回用户的所有订阅 我已经构建了这个获取订阅(最多50个)的函数,并且如果用户有超过50个订阅,则调用它来获取更多。
但我无法弄清楚如何合并每个函数调用的数组。 (最后看到while循环) 因为它现在可以工作,新的数组只会覆盖旧的数组,但我已经尝试将数组添加到主数组并返回它,但这只是将数组放入其中。
foreach循环返回一个如下所示的数组:
Array
(
[0] => Array
(
[channelName] => break
[channelLink] => https://www.youtube.com/channel/UClmmbesFjIzJAp8NQCtt8dQ
)
[1] => Array
(
[channelName] => kn0thing
[channelLink] => https://www.youtube.com/channel/UClmmbesFjIzJAp8NQCtt8dQ
)
[2] => Array
(
[channelName] => EpicMealTime
[channelLink] => https://www.youtube.com/channel/UClmmbesFjIzJAp8NQCtt8dQ
)
)
所以问题是while循环。有什么想法吗?
// Get an array with videos from a certain user
function getUserSubscriptions($username = false, $startIndex = 1, $maxResults = 50) {
// if username is not set
if(!$username) return false;
// get users 50 first subscriptions
// Use start-index to get the rest
$ch = curl_init('https://gdata.youtube.com/feeds/api/users/'.$username.'/subscriptions?v=2&max-results='.$maxResults.'&start-index='.$startIndex);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$subscriptionsXML = curl_exec($ch);
curl_close($ch);
// convert xml to array
$subscriptionsArray = XMLtoArray($subscriptionsXML);
// Ge total number of subscriptions
$totalNumberOfSubscriptions = $subscriptionsArray['FEED']['OPENSEARCH:TOTALRESULTS'];
// Parse array and clean it up
$s = 0;
$l = 0;
foreach($subscriptionsArray['FEED']['ENTRY'] as $subscriptionArray) {
// get link
foreach($subscriptionArray['LINK'] as $channelLinks) {
$channelLinkArray[$l] = $channelLinks;
$l++;
}
// save all into a more beautiful array and return it
$subscription[$s]['channelName'] = $subscriptionArray['YT:USERNAME']['DISPLAY'];
$subscription[$s]['channelLink'] = $channelLinkArray[1]['HREF'];
$s++;
}
// if we did not get all subscriptions, call the function again
// but this time increase the startIndex
while($totalNumberOfSubscriptions >= $startIndex) {
$startIndex = $startIndex+$maxResults;
$subscription = getUserSubscriptions($username, $startIndex);
}
return $subscription;
}
答案 0 :(得分:2)
当您进行递归调用时,问题似乎是:
$subscription = getUserSubscriptions($username, $startIndex);
这似乎是用返回的结果覆盖订阅数组,因此您只能构建最后一个数组。相反,你应该尝试合并数组:
$subscription = array_merge( $subscription, getUserSubscriptions($username, $startIndex) );
如果所有索引都是数字,则会将所有元素追加到数组的末尾。请参阅:http://php.net/manual/en/function.array-merge.php