如何在PHP中打印JSON数据
我想从下面的JSON结果中打印这些键“name”、“adminName1”、“countryCode”如何在PHP中打印JSON数据,php,json,Php,Json,我想从下面的JSON结果中打印这些键“name”、“adminName1”、“countryCode” { "geonames": [{ "adminCode1": "16", "lng": "74.19774", "distance": "2.95838", "geonameId": 1254611, "toponymName": "Thengode", "countryId": "1269750", "fcl": "P", "p
{
"geonames": [{
"adminCode1": "16",
"lng": "74.19774",
"distance": "2.95838",
"geonameId": 1254611,
"toponymName": "Thengode",
"countryId": "1269750",
"fcl": "P",
"population": 0,
"countryCode": "IN",
"name": "Thengode",
"fclName": "city, village,...",
"countryName": "India",
"fcodeName": "populated place",
"adminName1": "Maharashtra",
"lat": "20.51997",
"fcode": "PPL"
}]
}
如何正确地执行它?只需使用
json\u解码
并获取值即可。由于json\u decode
函数返回一个对象数组,因此需要使用->
来访问值
如果您的json字符串名称是$json
$arr = json_decode($json);
echo $arr->geonames[0]->name; //Thengode
echo $arr->geonames[0]->adminName1; //Maharashtra
echo $arr->geonames[0]->countryCode; //IN
您的json解码数组将是:
stdClass Object
(
[geonames] => Array
(
[0] => stdClass Object
(
[adminCode1] => 16
[lng] => 74.19774
[distance] => 2.95838
[geonameId] => 1254611
[toponymName] => Thengode
[countryId] => 1269750
[fcl] => P
[population] => 0
[countryCode] => IN
[name] => Thengode
[fclName] => city, village,...
[countryName] => India
[fcodeName] => populated place
[adminName1] => Maharashtra
[lat] => 20.51997
[fcode] => PPL
)
)
)
这很简单,看看吧
<?php
//just for error loggin
error_reporting(1);
ini_set('display_errors', true);
//json data
$json = '{
"geonames": [{
"adminCode1": "16",
"lng": "74.19774",
"distance": "2.95838",
"geonameId": 1254611,
"toponymName": "Thengode",
"countryId": "1269750",
"fcl": "P",
"population": 0,
"countryCode": "IN",
"name": "Thengode",
"fclName": "city, village,...",
"countryName": "India",
"fcodeName": "populated place",
"adminName1": "Maharashtra",
"lat": "20.51997",
"fcode": "PPL"
}]}';
//decoded json object
$jsonDataObject = json_decode($json);
//parsed variables
$name = $jsonDataObject->geonames[0]->name;
$adminName1 = $jsonDataObject->geonames[0]->adminName1;
$countryCode = $jsonDataObject->geonames[0]->countryCode;
?>
在尝试了你的代码之后,我收到了来自PHP的这封情书:-D PHP注意:尝试在线获取非objectcheck的属性:谢谢Frayne和Dan:-)尝试添加所有必需的字段…将JSON解码到数组中,使用array_keys()
获取密钥,然后获取你需要的密钥,先生,如果他需要这些钥匙,那么为什么需要解码??他早就认识他们了。
<?php
//just for error loggin
error_reporting(1);
ini_set('display_errors', true);
//json data
$json = '{
"geonames": [{
"adminCode1": "16",
"lng": "74.19774",
"distance": "2.95838",
"geonameId": 1254611,
"toponymName": "Thengode",
"countryId": "1269750",
"fcl": "P",
"population": 0,
"countryCode": "IN",
"name": "Thengode",
"fclName": "city, village,...",
"countryName": "India",
"fcodeName": "populated place",
"adminName1": "Maharashtra",
"lat": "20.51997",
"fcode": "PPL"
}]}';
//decoded json object
$jsonDataObject = json_decode($json);
//parsed variables
$name = $jsonDataObject->geonames[0]->name;
$adminName1 = $jsonDataObject->geonames[0]->adminName1;
$countryCode = $jsonDataObject->geonames[0]->countryCode;
?>