所以我在玩Google 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;
}
好主意。但是,它似乎返回null並且array_merge將返回錯誤。 – Patrik 2012-04-11 22:50:15
啊,你應該在你的'foreach'之前將$ subscription初始化爲一個空數組,以防萬一不符合條件。嘗試將'$ subscription = array();'放在函數頂部附近。 – Dan 2012-04-11 22:58:21
哈哈真棒。有用!謝謝 :) – Patrik 2012-04-11 23:14:13