如何在PHP中获取数组中的数组

时间:2013-04-06 17:29:03

标签: php api youtube

下面的代码段从YouTube API获取用户的播放列表,并将标题和网址存储在$播放列表数组中。

<?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 ) )

如何访问其中一个播放列表数组并获取标题和网址?

1 个答案:

答案 0 :(得分:0)

只需做一个for循环或foreach然后你可以像foreach一样使用它:

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