2016-09-27 38 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" 
        } 
       } 
      }, 
... 
] 

私の次のステップは、都合Videoクラスのインスタンスに各項目をマッピングし、最終的に私のデータベースに各ビデオ項目を格納し、映像関連データを含む配列をつかむだろう。どのように私はそれを達成することができます誰も考えを持っていますか?

答えて

1

これを実行するには、以下を使用します。あなたがあなたの質問で提供したAPIの応答から、オブジェクトの配列があり、それらのオブジェクトの中にオブジェクトがあるので、2つのループが必要です。

// $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, 
      ... 
     ]); 
    } 
} 
関連する問題