PHP Fatal error: Cannot use object of type stdClass as array in错误

在使用php curl时,返回了一个json字符串,然后试图使用json_decode()方法对其进行转换,例子代码如下:

    private function callGoogleMapApi($address, $city, $zip) {
        $result = "failure";
        $address = urlencode($address.", ".$city.", ".$zip);
        $url = "http://maps.google.com/maps/api/geocode/json?address=".$address;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close ($ch);

        if ($output === FALSE) {
            //echo "cURL Error: " . curl_error ( $ch );
            //TODO
        }else{
            $output = str_replace("\n", "", $output);
            $output = str_replace("\r", "", $output);
            $output = str_replace("\t", "", $output);
            $output = json_decode($output);
            if("OK" == $output["status"]){
                $result = "success";
            }
        }

        return $result;
    }

然后就一直报
if("OK" == $output["status"]){

这一行出错,错误信息如标题所示,$output的值如下所示:


{
    "results": [
        {
            "address_components": [
                {
                    "long_name": "353",
                    "short_name": "353",
                    "types": [
                        "street_number"
                    ]
                },
                {
                    "long_name": "Broadway",
                    "short_name": "Broadway",
                    "types": [
                        "route"
                    ]
                },
                {
                    "long_name": "Downtown",
                    "short_name": "Downtown",
                    "types": [
                        "neighborhood",
                        "political"
                    ]
                },
                {
                    "long_name": "Albany",
                    "short_name": "Albany",
                    "types": [
                        "locality",
                        "political"
                    ]
                },
                {
                    "long_name": "Albany County",
                    "short_name": "Albany County",
                    "types": [
                        "administrative_area_level_2",
                        "political"
                    ]
                },
                {
                    "long_name": "New York",
                    "short_name": "NY",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "United States",
                    "short_name": "US",
                    "types": [
                        "country",
                        "political"
                    ]
                },
                {
                    "long_name": "12207",
                    "short_name": "12207",
                    "types": [
                        "postal_code"
                    ]
                }
            ],
            "formatted_address": "353 Broadway, Albany, NY 12207, USA",
            "geometry": {
                "location": {
                    "lat": 42.6480516,
                    "lng": -73.74957599999999
                },
                "location_type": "ROOFTOP",
                "viewport": {
                    "northeast": {
                        "lat": 42.6494005802915,
                        "lng": -73.7482270197085
                    },
                    "southwest": {
                        "lat": 42.6467026197085,
                        "lng": -73.7509249802915
                    }
                }
            },
            "place_id": "ChIJ192n-iAK3okRc4CgKCDF21s",
            "types": [
                "street_address"
            ]
        }
    ],
    "status": "OK"
}

怎么看,这个格式都没有问题啊,于是百思不得其解,上网查查,看到了这篇文章,试了试,发现果然可以用。

方法有两种:


第一种方式:

json_decode($output, true)
看官方文档,

mixed  json_decode (  string $json [,  bool $assoc = false [,  int $depth = 512 [,  int $options = 0 ]]] )

接受一个 JSON 格式的字符串并且把它转换为 PHP 变量

参数 

json

待解码的 json string 格式的字符串。

This function only works with UTF-8 encoded data.

assoc

当该参数为 TRUE 时,将返回 array 而非 object 。

depth

User specified recursion depth.

options

Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)

返回值 

Returns the value encoded in json in appropriate PHP type. Values truefalse and null (case-insensitive) are returned as TRUEFALSE andNULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

当,第二个参数为true时,就会转换为数组,而不是object,对数组操作可以使用$output["statue"],且不论结果对不对。


第二种方式:

$output->status
指向key这种方式,代码如下:

    private function callGoogleMapApi($address, $city, $zip) {
        $result = "failure";
        $address = urlencode($address.", ".$city.", ".$zip);
        $url = "http://maps.google.com/maps/api/geocode/json?address=".$address;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close ($ch);

        if ($output === FALSE) {
            //echo "cURL Error: " . curl_error ( $ch );
            //TODO
        }else{
            $output = str_replace("\n", "", $output);
            $output = str_replace("\r", "", $output);
            $output = str_replace("\t", "", $output);
            $output = json_decode($output);
            if("OK" == $output->status){
                $result = "success";
            }
        }

        return $result;
    }

发现可以用,得到了正确的结果。

其实这一点我就不太懂了,因为有时候对object确实可以使用["key"]的方式取值,而现在不可以,我就不知道真实原因了。


原文链接:http://blog.csdn.net/21aspnet/article/details/6599777

你可能感兴趣的:(PHP)