Estou tendo problemas com json, não entendo por que meu código não funciona. Eu quero colocar o [secondary_text] => United Kingdom
em uma variável php, mas estou recebendo este Aviso o tempo todo:
Aviso : Tentando obter 'previsões' de propriedade de não-objeto em C: ......... \ CCPSeven.php na linha 153
Meu código:
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);
O 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
)
Você pode achar um pouco mais simples decodificar a string JSON para uma matriz associativa PHP em vez de um objeto:
$jsondecode2 = json_decode($htmlj, true);
$Country = $jsondecode2['predictions'][0]['structured_formatting']['secondary_text'];
A segunda opção na json_decode
função diz a ela para retornar uma matriz em vez de um objeto. Mais informações aqui: http://php.net/manual/en/function.json-decode.php
Em seu código de amostra, parece que você perdeu um ['predictions']
pouco do seu loop foreach? Aqui estão dois exemplos de estilo de objeto e matriz:
// 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;
}
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras