如何从多级json中检索值

时间:2014-03-13 05:32:36

标签: php json

我试图从这个json条目的各个部分获取值。

{
    "gallery_show": "1",
    "gallery": {
        "path": ["images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg"],
        "title": ["", "", "", "", "", ""],
        "caption": ["", "", "", "", "", ""],
        "thumb": ["\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg", 
        "\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg", 
        "\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg", 
        "\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg", 
        "\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg", 
        "\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg"]
    },
    "videos_show": "1",
    "videos": {
        "title": ["Arnie", "Arnie", "Arnie", "Arnie", "Arnie"],
        "sharelink": ["http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY"]
    },
    "attachments_show": "1",
    "attachments": {
        "path": ["images\/slide2.jpg", "images\/slide1.jpg"],
        "title": ["Attchment", "Attchment"],
        "caption": ["Attachment Description", "Attachment Description"]
    },
    "links_show": "1",
    "links": {
        "title": ["Link1", "Link2"],
        "httplink": ["http:\/\/www.mydomain.com", "http:\/\/www.mydomain.com"],
        "targetlink": ["_blank", "_blank"]
    }
}

如果我使用这种方法

$entries= json_decode($this->item->entries);

然后我回应这个

echo $entries->gallery_show;

我得到了理想的结果= 1

但是如果gallery_show = 1并且将它们显示为我可以在我的php中使用的值,我现在如何得到它下面的东西?

对这个老大脑的任何帮助都会非常感激。

提前干杯 强尼

1 个答案:

答案 0 :(得分:1)

你可以这样做......

$arr = json_decode($json);
foreach($arr as $k=>$v)
{
    if($k=='gallery_show' && $v==1)
    {
        foreach($arr->gallery->path as $path)
        {
            echo "<img src=$path />";
        }
        break;
    }
}

Demo

代码更新..

$arr = json_decode($json);
$i=0;
foreach($arr as $k=>$v)
{
    if($k=='gallery_show' && $v==1)
    {

        foreach($arr->gallery as $gall)
        {

            echo "Title :".$arr->gallery->title[$i]."<br/>";
            echo "Caption :".$arr->gallery->caption[$i]."<br/>";
            echo "Thumbnail :".$arr->gallery->thumb[$i]."<br>";
            echo "<img src=".$arr->gallery->path[$i]." /><br>";
            $i++;
        }
        break;
    }
}

Demo