【发布时间】:2019-04-13 12:10:16
【问题描述】:
我有两个 JSON 文件,每个文件都包含一个具有相同结构但数据不同的 FeatureCollection。我正在尝试将它们组合成一个 JSON 文件作为包含所有数据的单个 FeatureCollection。我几乎做到了这一点,但“FeatureCollection”在文件开头重复,使其无效 JSON。
我认为这与我分别对两个文件进行 JSON 编码的方式有关,然后在我组合它们时再次编码,但经过一天尝试各种组合后,我还没有设法弄明白。
这是创建第一个 JSON 文件的代码(其中 $results 由数据库查询生成):
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while ( $results->fetch() ) {
$feature = array(
'type' => 'Feature',
'properties' => array(
'name' => $results->field('name')
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array((float)$results->field('long'), (float)$results->field('lat'))
)
);
array_push($geojson['features'], $feature);
};
// // Create JSON file
$fp = fopen('file1.json', 'w');
fwrite($fp, json_encode($geojson));
fclose($fp);
第二个文件(file2.json)同样创建,eg:
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while ( $results->fetch() ) {
$feature = array(
'type' => 'Feature',
'properties' => array(
'name' => $results->field('name')
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array((float)$results->field('long'), (float)$results->field('lat'))
)
);
array_push($geojson['features'], $feature);
};
// // Create JSON file
$fp = fopen('file2.json', 'w');
fwrite($fp, json_encode($geojson));
fclose($fp);
然后我使用以下代码将它们组合起来:
$jsonString = file_get_contents('file2.json');
$jsonString2 = file_get_contents('file1.json');
$data = json_decode($jsonString, true);
$data2 = json_decode($jsonString2, true);
$op = array_merge_recursive( $data, $data2 );
$fp = fopen('file3.json', 'w');
fwrite($fp, json_encode($op));
fclose($fp);
生成的文件基本上没问题,它包含我需要的所有数据并且格式正确,除了文件开头它具有以下事实:
{"type":["FeatureCollection","FeatureCollection"],"features":[{"type":"Feature","properties":{"name":"......etc
代替:
{"type":["FeatureCollection"],"features":[{"type":"Feature","properties":{"name":"......etc
我不明白为什么一开始有两个“FeatureCollection”实例,或者如何只产生一个。
【问题讨论】: