Php 如何在json文件中插入新字段
我有一个像这样的JSON文件Php 如何在json文件中插入新字段,php,json,Php,Json,我有一个像这样的JSON文件 { "AAL": { "id": "32313", "airport_name": "Aalborg", "latitude": "57.1", "longitude": "9.85", "timezone": "2", "dst_indicator": "E", "city": "Aalborg", "country": "Den
{
"AAL": {
"id": "32313",
"airport_name": "Aalborg",
"latitude": "57.1",
"longitude": "9.85",
"timezone": "2",
"dst_indicator": "E",
"city": "Aalborg",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
},
"AAR": {
"id": "32314",
"airport_name": "Tirstrup",
"latitude": "56.15",
"longitude": "10.2167",
"timezone": "2",
"dst_indicator": "E",
"city": "Aarhus",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
}
}
我需要向它添加一个新字段,并使用php获得如下结果。任何帮助都将不胜感激
{
"AAL": {
"station_code":"AAL",
"id": "32313",
"airport_name": "Aalborg",
"latitude": "57.1",
"longitude": "9.85",
"timezone": "2",
"dst_indicator": "E",
"city": "Aalborg",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
},
"AAR": {
"station_code":"AAR",
"id": "32314",
"airport_name": "Tirstrup",
"latitude": "56.15",
"longitude": "10.2167",
"timezone": "2",
"dst_indicator": "E",
"city": "Aarhus",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
}
}
您应该将json解析为php变量。这里添加额外字段并将其解析回json
您可以通过这种方式实现输出
$data= '{
"AAL": {
"id": "32313",
"airport_name": "Aalborg",
"latitude": "57.1",
"longitude": "9.85",
"timezone": "2",
"dst_indicator": "E",
"city": "Aalborg",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
},
"AAR": {
"id": "32314",
"airport_name": "Tirstrup",
"latitude": "56.15",
"longitude": "10.2167",
"timezone": "2",
"dst_indicator": "E",
"city": "Aarhus",
"country": "Denmark",
"country_code": "DK",
"region": "TC1",
"listing_display": "true",
"pseudonyms": ""
}
}';
$arrData = json_decode($data,true);
foreach($arrData as $key=>$val){
$arrData[$key]['station_code']=$key;
}
echo json_encode($arrData);
exit;
PHP中的JSON解析
要读取包含JSON数据的文件,请执行以下操作:
$json_array_assc = json_decode(file_get_contents($file_name), true);
要向数组中添加字段,可以执行以下操作:
$json_array_assc["NEWDATA"]=array('newdata1'=>'foo1','newdata2'=>'foo2');
要将新数据写入文件,请使用:
file_put_contents($file_name, json_encode($json_array_assc));
或者只需在控制台窗口上打印阵列:
echo "<pre>";
print_r($json_array_assc);
仔细阅读并阅读。
echo json_encode($json_array_assc);