PHP foreach array IDs


PHP foreach array IDs

我有一个foreach循环,它应该通过JSON循环,并使用Youtube api返回JSON中列出的每个视频的适当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和其他信息。

我觉得这是一个简单的解决办法,但我一辈子都想不出来。如果有任何帮助,我将不胜感激!此外,如果我做错了这一切,建议也很感激!

谢谢!

我对您的代码做了一些处理。我修改了你的课。我已将plurrar视频重命名为视频(单数)。

然后我添加了一个属性$id,因为属性的名称应该很简单,并且表示我们想要存储在其中的数据。

然后,我为$id属性添加了getter和setter。

我不知道$url,所以我只写了一个简单的JSON字符串。我试图模仿您在代码中使用的结构。

然后,我在new 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);

在您的代码中,类视频包含两个函数

setVideoTitle(...),
getVideoTitle()

但在你的前臂上,你已经呼叫了$videos->getVideoUrl() , $videos->setVideoUrl(...)

这是什么???