开发者

why json_decode isnt working for some code?

for this json api response I am able to parse with json_decode:

 $string = '{"name": "Google",
     "permalink": "google",
     "homepage_url": "http://google.com",
     "blog_url": "http://googleblog.blogspot.com",
     "blog_feed_url": "http://googleblog.blogspot.com/feeds/posts/default?alt=rss",
     "twitter_username": "google",
     "category_code": "search",
     "number_of_employees": 20000,
     "founded_year": 1998,
     "founded_month": 9,
     "founded_day": 7,// 开发者_运维百科bla bla.....}';

$obj=json_decode($string);
echo $obj->number_of_employees."<br>";// 20000
echo $obj->founded_year; //1998

I am getting result with above but getting blank result with below one:

$string =  '{"offices":
  [{"description": "Google Headquarters",
    "address1": "1600 Amphitheatre Parkway",
    "address2": "",
    "zip_code": "",
    "city": "Mountain View",
    "state_code": "CA",
    "country_code": "USA",//blah blah }]//blah blah...}';

$obj=json_decode($string);
echo $obj->address1."<br>";// ""
echo $obj->city; //""

I am aware that address1 is again inside another array or loop but dont know how to retrieve it...any ideas??


You will need something like:

foreach($obj->offices as $office) {
    echo $office->address1; // The first would be '1600 Amphitheatre Parkway'
}

To view contents of your decoded json do something like the following:

echo "<pre>";
print_r($obj);
echo "</pre>";

In your case this would give you:

stdClass Object
(
    [offices] => Array
        (
            [0] => stdClass Object
                (
                    [description] => Google Headquarters
                    [address1] => 1600 Amphitheatre Parkway
                    [address2] => 
                    [zip_code] => 
                    [city] => Mountain View
                    [state_code] => CA
                    [country_code] => USA
                )

        )

)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜