2016-05-12 78 views
0

我有一個foreach循環,應該通過JSON循環,並使用Youtube API返回JSON中列出的每個視頻的相應ID。 這是我的代碼:PHP foreach數組ID

class Videos { 
    private $mVideoUrl; 

    function setVideoTitle($videoUrl){ 
     $this->mVideoUrl= $videoUrl; 
    } 

    function getVideoTitle(){ 
     return $this->mVideoUrl; 
    } 
} 

$jsonFile = file_get_contents($url); 
$jfo = json_decode($jsonFile); 
$items = $jfo->items; 
$vidArray = array(); 

foreach ($items as $item){ 
    if(!empty($item->id->videoId)){ 
     $Videos = new Videos; 
     $Videos->setVideoUrl($item->id->videoId); 
     $id = $Videos->getVideoUrl(); 
     array_push($vidArray, $id); 
    } 
    echo $vidArray[0]; 
} 

問題是,陣列推工作正常,但它是僅加入該列表中的第一ID只對每次循環迭代當我回聲它。當我回顯$ id變量時,它會打印所有的ID。

最終,我希望能夠爲每個視頻創建一個對象,存儲它的ID和其他信息。

我覺得這是一個簡單的修復,但我無法弄清楚我的生活。 我將不勝感激任何幫助! 此外,如果我對這一切都錯了,建議也表示讚賞!

謝謝!

+0

'echo $ vidArray [0];'只回應第一個元素。試試'print_r($ vidArray);' – AbraCadaver

回答

1

我已經玩了一點你的代碼。我修改了你的課程。我已將plurar視頻重新命名爲Video(單數)。

然後我添加了一個屬性$ id,因爲屬性的名稱應該很簡單,並且表示我們要存儲在其中的數據。

然後我添加了$ id屬性的getter和setter。

我不知道$ url,所以我只寫了簡單的JSON字符串。我試圖模仿你在代碼中使用的結構。

然後,我添加了()到新的Video()的末尾,以調用正確的構造函數。

而不是將元素推入數組中,我使用正確的$ array [$ index] =賦值。

最後一件事,我已經寫出了foreach循環中的數據。而且我正在使用var_export來獲取正確的php代碼,如果重定向到另一個文件。

<?php 

class Video 
{ 
    private $mVideoUrl; 
    private $id; // added id attribute 

    /** 
    * @return mixed 
    */ 
    public function getId() // added getter 
    { 
     return $this->id; 
    } 

    /** 
    * @param mixed $id 
    */ 
    public function setId($id) // added setter 
    { 
     $this->id = $id; 
    } 


    function setVideoTitle($videoUrl) 
    { 
     $this->mVideoUrl = $videoUrl; 
    } 

    function getVideoTitle() 
    { 
     return $this->mVideoUrl; 
    } 
} 

// ignored for now 
// $jsonFile = file_get_contents($url); 
$jsonFile = '{"items": [ 
     { "id": { "videoId": 1, "url": "http://www.youtube.com/1" } }, 
     { "id": { "videoId": 2, "url": "http://www.youtube.com/2" } }, 
     { "id": { "videoId": 3, "url": "http://www.youtube.com/3" } }, 
     { "id": { "videoId": 4, "url": "http://www.youtube.com/4" } }, 
     { "id": { "videoId": 5, "url": "http://www.youtube.com/5" } } 
    ] 
}'; 

$jfo = json_decode($jsonFile); 

$items = $jfo->items; 
$vidArray = array(); 

foreach ($items as $item) 
{ 
    if (!empty($item->id->videoId)) 
    { 
     $Video = new Video(); // added brackets 

     $Video->setId($item->id->videoId); // changed to setId 
     $Video->setVideoTitle($item->id->url); 
     $id = $Video->getId(); 
     $vidArray[$id] = $Video; 
    } 

} 

// write out all data 
var_export($vidArray); 
1

在你的代碼的類影片包含兩個功能

setVideoTitle(...), 
getVideoTitle() 

但在你的foreach你叫$videos->getVideoUrl() , $videos->setVideoUrl(...)

這是什麼???