2013-04-06 64 views
-3

下面的代碼從YouTube API獲取用戶的播放列表,並將標題和URL存儲在$ playlists數組中。如何在PHP中獲取陣列中的陣列

<?php 

function get_playlists($username) 
{ 
    if ((time() - filemtime("{$GLOBALS['path']}/cache/playlist_cache.txt")) > 3600) 
    { 
     $start = 1; 
     $playlists = array(); 

    do 
    { 
     $data = "http://gdata.youtube.com/feeds/api/users/{$username}/playlists?start-index=1&max-results=50&v=2&alt=json"; 
     foreach (json_decode(file_get_contents("$data"))->feed->entry as $playlist) 
     { 
      $url = (array)$playlist->link[0]; 
      $playlists[] = array(
       'title' => $playlist->title->{'$t'}, 
       //'desc' => $playlist->{'media$group'}->{'media$description'}->{'$t'}, 
       'url' => $playlist->{'yt$playlistId'}->{'$t'}, 
       //"yt$playlistId":{"$t":"PL4nGg2mJgyg-eYKyoVfOPfncFnRFdlgTq"} 
      ); 

      $last = (array)$playlist->link[1]; 
     } 
     $start +=50; 
    }while (empty($last) === false && $last['rel'] === 'next'); 

     file_put_contents("{$GLOBALS['path']}/cache/playlist_cache.txt", serialize($playlists)); 
    }else{ 
     $playlists = unserialize(file_get_contents("{$GLOBALS['path']}/cache/playlist_cache.txt")); 
    } 

    return $playlists; 
} 

?> 

輸出結果:

Array ([0] => Array ([title] => FTB Yogcraft - w/ Dapaka [url] => PL4nGg2mJgyg-eYKyoVfOPfncFnRFdlgTq) [1] => Array ([title] => Vlogs [url] => PL4nGg2mJgyg9a4BOTK6L8lW-JYNOiKRJa) [2] => Array ([title] => One Incompetent Moron Completes - Metro 2033 [url] => PL4nGg2mJgyg9fV9r7oEJUrOoKfN4V711-) [3] => Array ([title] => Minecraft - Herobrine's Mansion [url] => PL4nGg2mJgyg_xeSCck018tccbLVL5EiSY) [4] => Array ([title] => IRL Video's [url] => PL4nGg2mJgyg_vwUIBShxEU2-LzY9xpMdt) [5] => Array ([title] => One Incompetent Moron Plays - McPixel [url] => PL4nGg2mJgyg_5CU-6ItfLVdC1l5isBwXy) [6] => Array ([title] => One Incompetent Moron Plays - The Binding Of Isaac [url] => PL4699B89F55DDAEEC) [7] => Array ([title] => Minecraft - Mod Reviews [url] => PLA9EB70BCA281692B) [8] => Array ([title] => Minecraft - Project: "City" [url] => PLAC4E2CD6E19EB091) [9] => Array ([title] => One Incompetent Moron Plays: Sumotori Dreams [url] => PLE1F0B8801427BA8F) [10] => Array ([title] => Let's Fail: DayZ [url] => PLD4298D8BCF2F0259) [11] => Array ([title] => Portal 2 - Custom Maps [url] => PL15D0E6D108971276)) 

我怎麼會進入播放列表陣列中的一個,並得到了標題和網址?

+0

這一點已經在這裏找到答案:http://stackoverflow.com/questions/1544176/accessing -array-arrays-in-php – madcrazydrumma 2013-04-06 17:35:25

回答

0

只是做一個for循環或的foreach,然後你可以在的foreach的情況下,使用這樣的:

$playlists = get_playlists('username') 
foreach($playlists as $playlist) 
{ 
    echo $playlist['title']; 
} 
+0

對不起,很難說出這個問題。回聲$ playlist ['title']會導致所有打印的標題,如果只有一個結果,那麼您只能獲得一個 – GiggleSquid 2013-04-06 17:36:31

+0

,那麼您可以直接像$ playlists [0] ['title']那樣訪問它沒有foreach循環。其中0是陣列的關鍵。 – CGeorges 2013-04-06 17:38:44

+0

啊,我在之前的foreach循環中試過。謝謝,這正如預期的那樣工作:D – GiggleSquid 2013-04-06 17:40:43