So I’m playing with Googles YouTube API and I want to return all subscriptions from a user.
I have built this function that gets the subscriptions (max 50) and calls it self to get more if the user has over 50 subscriptions.
But I can’t figure out how to merge the arrays from each function call. (see the while loop in the end).
As it works now the new arrays will just overwrite the old ones but I have tried adding the arrays to a main array and returning it but that will just place the arrays in them self.
The foreach loop returns an array that looks like this:
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
)
)
So the problem is the while loop. Got any ideas?
// 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;
}
The problem appears to be when you’re making the recursive call:
$subscription = getUserSubscriptions($username, $startIndex);This appears to be overwriting the subscription array with the returned results, so you would only get the last array built. Instead you should try merging the arrays:
$subscription = array_merge( $subscription, getUserSubscriptions($username, $startIndex) );This will append all elements to the end of the array if all the indexes are numeric. See: http://php.net/manual/en/function.array-merge.php