如何将这个Json数据放入Php变量?

时间:2017-12-31 10:41:30

标签: php html json

我遇到了json的问题,我不知道为什么我的代码不起作用。我想将[secondary_text] => United Kingdom放入php变量中,但我一直收到此通知:

  

注意:尝试获取非对象的属性“预测”   C:......... \ CCPSeven.php第153行

我的代码:

  header('Content-Type: application/json');
    $htmlj = file_get_html('https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key=*****&input=London&language=en',false);
    $jsondecode2 = json_decode($htmlj);
        foreach ($jsondecode2 as $jsonforeach2) {
        $Country = ($jsonforeach2->description->structured_formatting->secondary_text);
    }
    print_r($Country);

Json:

stdClass Object
(
    [predictions] => Array
        (
            [0] => stdClass Object
                (
                    [description] => London, United Kingdom
                    [id] => *****+
                    [matched_substrings] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [length] => 6
                                    [offset] => 0
                                )

                        )

                    [place_id] => ChIJdd4hrwug2EcRmSrV3Vo6llI
                    [reference] => *****
                    [structured_formatting] => stdClass Object
                        (
                            [main_text] => London
                            [main_text_matched_substrings] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [length] => 6
                                            [offset] => 0
                                        )

                                )

                            [secondary_text] => United Kingdom
                        )

1 个答案:

答案 0 :(得分:1)

您可能会发现将JSON字符串解码为PHP关联数组而不是对象更简单:

$jsondecode2 = json_decode($htmlj, true);
$Country = $jsondecode2['predictions'][0]['structured_formatting']['secondary_text'];

json_decode函数的第二个选项告诉它返回一个数组而不是一个对象。更多信息:http://php.net/manual/en/function.json-decode.php

在您的示例代码中,看起来您可能错过了foreach循环中的['predictions']位?以下是对象和数组样式的两个示例:

// Object style
$jsondecode2 = json_decode(file_get_contents($htmlj));
foreach ($jsondecode2->predictions as $jsonforeach2) {
    $Country = $jsonforeach2->structured_formatting->secondary_text;
    print PHP_EOL . "Object style: Country: " . $Country;
}

// Associative array style
$jsondecode2 = json_decode(file_get_contents($htmlj), true);
foreach ($jsondecode2['predictions'] as $jsonforeach2) {
    $Country = $jsonforeach2['structured_formatting']['secondary_text'];
    print PHP_EOL . "Array style: Country: " . $Country;
}