2010-07-06 47 views
0

這個JSON API響應我能夠與json_decode解析:爲什麼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 

我下面一個得到的結果與上面,但得到空白結果:

$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; //"" 

我知道地址1再次在另一個數組或循環內,但不知道如何檢索它...任何想法?

回答

3

你會需要這樣的東西:

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

要查看解碼JSON的內容做類似如下:

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

你的情況,這將給你:

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

非常感謝它正在工作....還有一個問題,我沒有提到所有結果在這裏... adress1進行multipple結果說1600露天劇場Parkway,112 S. Main St.10 10th Street NEPlaza,以及更多......我如何控制這個?我想要說只有一個或兩個地址.. – mathew 2010-07-06 08:07:57

+0

您可能使用implode函數,$ addresses = implode(「,」,$ address1);這將把所有地址放入一個由逗號分隔的數組中 – Lizard 2010-07-06 08:25:26

+0

哦,我總是忘記這些命令... $ addresses = explode(「,」,$ address1); echo $ addresses [0];這將給出結果... – mathew 2010-07-06 09:07:28

相關問題