0

所以我正在使用 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;
}
4

1 回答 1

2

问题似乎出在您进行递归调用时:

$subscription = getUserSubscriptions($username, $startIndex);

这似乎用返回的结果覆盖了订阅数组,所以你只会得到最后一个构建的数组。相反,您应该尝试合并数组:

$subscription = array_merge( $subscription, getUserSubscriptions($username, $startIndex) );

如果所有索引都是数字,这会将所有元素附加到数组的末尾。见: http: //php.net/manual/en/function.array-merge.php

于 2012-04-11T22:21:25.247 回答