从调用它的函数合并数组



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

问题似乎是当您进行递归调用时:

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

这似乎是用返回的结果覆盖订阅数组,因此您只会生成最后一个数组。相反,您应该尝试合并数组:

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

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

相关内容

  • 没有找到相关文章

最新更新