访问JSON PHP数组问题

时间:2013-08-19 14:00:24

标签: php json

嗨我有这个JSON响应,我想访问每个页面的图像,当每个页面的id未知(随机生成)时,我将如何访问这些图像?

string(310) "{"query":{"redirects":[{"from":"Romerolagus diazi",
                                       "to":"Volcano rabbit"}],
       "pages":{"4733563":
          {"pageid":4733563,
           "ns":0,
           "title":"Volcano rabbit",
           "images":[
              {"ns":6,"title":"File:Question book-new.svg"},
              {"ns":6,"title":"File:Romerolagus diazi (dispale) 001.jpg"},
              {"ns":6,"title":"File:Status iucn2.3 EN.svg"}
                    ]
           }}}}" 

我的尝试:

$result = $json->pages[0];
echo "{$result->images}";

2 个答案:

答案 0 :(得分:0)

您正在尝试访问无效元素。请尝试以下方法:

echo $json->query->pages->{4733563}->images[1]->title;

输出:

File:Romerolagus diazi (dispale) 001.jpg

<强> Demo 1!


或者,如果您想要一个关联数组,可以将json_decode中的第二个参数设置为TRUE

$string = '...';
$json = json_decode($string, true);
print_r($json['query']['pages']['4733563']['images'][0]);

输出:

Array
(
    [ns] => 6
    [title] => File:Question book-new.svg
)

<强> Demo 2!

答案 1 :(得分:0)

你可以试试这个。这是有效的

CODE SAMPLE ONE : 
    $var = json_decode('{"query":{"redirects":[{"from":"Romerolagus diazi","to":"Volcano rabbit"}],"pages":{"4733563":{"pageid":4733563,"ns":0,"title":"Volcano rabbit","images":[{"ns":6,"title":"File:Question book-new.svg"},{"ns":6,"title":"File:Romerolagus diazi (dispale) 001.jpg"},{"ns":6,"title":"File:Status iucn2.3 EN.svg"}]}}}} ');
    echo "<pre>"; 
    foreach($var->query->pages as $da) 
    {
    $image_array= $da->images;  
    $i=0; 
    foreach($image_array as $img)
    {$i++;
    echo "<Br/> ".$i.")".$images = $img->title;     

    }

    }




OR

 CODE SAMPLE TWO :


$var = json_decode('{"query":{"redirects":[{"from":"Romerolagus diazi","to":"Volcano rabbit"}],"pages":{"4733563":{"pageid":4733563,"ns":0,"title":"Volcano rabbit","images":[{"ns":6,"title":"File:Question book-new.svg"},{"ns":6,"title":"File:Romerolagus diazi (dispale) 001.jpg"},{"ns":6,"title":"File:Status iucn2.3 EN.svg"}]}}}} ',true);
echo "<pre>";

foreach($var['query']['pages'] as $da) 
{
$image_array= $da['images'];    
$i=0; 
foreach($image_array as $img)
{$i++;
echo "<Br/> ".$i.")".$images = $img['title'];   

}

}

Output : 


 1)File:Question book-new.svg
 2)File:Romerolagus diazi (dispale) 001.jpg
 3)File:Status iucn2.3 EN.svg