【问题标题】:why json_decode isnt working for some code?为什么 json_decode 不适用于某些代码?
【发布时间】:2010-07-06 07:26:15
【问题描述】:

对于这个 json api 响应,我可以使用 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; //""

我知道 address1 再次在另一个数组或循环中,但不知道如何检索它...有什么想法吗??

【问题讨论】:

    标签: php json loops object


    【解决方案1】:

    你需要这样的东西:

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

    【讨论】:

    • 非常感谢它正在工作....还有一个问题我没有在这里提到所有结果...adress1 带有多个结果,例如 1600 Amphitheatre Parkway、112 S. Main St.10 10th Street NEPlaza 和更多...我该如何控制这个?我只想说一两个地址..
    • 你可能会使用 implode 函数,$addresses = implode(",", $address1);这会将所有地址放入以逗号分隔的数组中
    • 哦,我总是忘记这些命令...$addresses = explode(",", $address1);回声$地址[0];这将给出结果...
    • 我收到 Invalid implode function 错误消息...这是为什么呢??
    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2013-08-12
    • 1970-01-01
    • 2022-01-14
    • 2012-10-28
    • 2020-08-05
    相关资源
    最近更新 更多