2016-05-12 74 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(...)

这是什么???