0

嗨,我有这个 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}";
4

2 回答 2

0

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

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

输出:

File:Romerolagus diazi (dispale) 001.jpg

演示 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
)

演示 2!

于 2013-08-19T14:06:12.547 回答
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
于 2013-08-19T14:07:43.730 回答