2016-09-27 48 views
1

我正嘗試使用Laravel 5.3構建基於Youtube的應用程序。使用庫我可以成功從播放列表中檢索數據並顯示它。它的格式是這樣的:使用Laravel 5.3將Youtube API數據導入到db中

[ 
    { 
     0: { 
      kind: "youtube#playlistItem", 
      etag: ""I_8x5t5r66_FSaexwefRREftGc0/BO3zvggHrzgTTh_ZhXr745ww"", 
      id: "UExDQXc3VFJvaVBIX2VuXzMtcThnWW9ZZUc4YlVmX2dOUC4wMTcyMDhGQUE4NTIzM0Y5", 
      snippet: { 
       publishedAt: "2014-10-06T15:50:12.000Z", 
       channelId: "UCGT2vvwtBJ-0edGHEj5Tv67Q", 
       title: "S'More - La ricetta dei biscotti", 
       description: "Sul blog la storia, la ricetta e le foto", 
       thumbnails: { 
        default: { 
         url: "https://i.ytimg.com/vi/Hug-iFvDS3s/default.jpg", 
         width: "120", 
         height: "90" 
        }, 
        medium: { 
         url: "https://i.ytimg.com/vi/Hug-iFvDS3s/mqdefault.jpg", 
         width: "320", 
         height: "180" 
        }, 
        high: { 
         url: "https://i.ytimg.com/vi/Hug-iFvDS3s/hqdefault.jpg", 
         width: "480", 
         height: "360" 
        }, 
        standard: { 
         url: "https://i.ytimg.com/vi/Hug-iFvDS3s/sddefault.jpg", 
         width: "640", 
         height: "480" 
        }, 
        maxres: { 
         url: "https://i.ytimg.com/vi/Hug-iFvDS3s/maxresdefault.jpg", 
         width: "1280", 
         height: "720" 
        } 
        }, 
        channelTitle: "Ricette di Famiglia", 
        playlistId: "PLCAB2ddt6H_en_3-q8gRfTYsbUf_gNP", 
        position: "0", 
        resourceId: { 
         kind: "youtube#video", 
         videoId: "Hug-iFvDS3s" 
        } 
       } 
      }, 
... 
] 

我的下一個步驟將是抓住包含視頻相關數據陣列,方便每個項目映射到一個視頻類的實例,最後每個視頻項目保存到我的數據庫。有沒有人有任何想法,我怎麼能實現這一目標?

回答

1

您可以使用以下方法完成此操作。從您在問題中提供的API響應中,有一個對象數組,並且這些對象內部有對象,因此您需要兩個循環。

// $json is the JSON response you get from the API 
$entities = json_decode($json); 

foreach ($entities as $entity) { 
    $items = get_object_vars($entity); 

    // Each $item is a video object from the API response 
    foreach ($items as $item) { 
     // Create a new Video object and persist it in the DB 
     $video = new Video(); 
     $video->create([ 
      'kind' => $item->kind, 
      'published_at' => $item->publishedAt, 
      ... 
     ]); 
    } 
}