如何将 2 JSON 个文件合并为一个 JSON FeatureCollection

How to merge 2 JSON files into one JSON FeatureCollection

我有两个 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)以同样的方式创建,例如:

$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" 实例,或者如何只产生一个。

当您合并两组数据时,它们都有自己的 "type" 副本,合并将创建包含这两项的输出。

考虑...

$data = [ "type" => "FeatureCollection"];
$data2 = [ "type" => "FeatureCollection"];

$op = array_merge_recursive( $data, $data2 );

print_r($op);

这将输出

Array
(
    [type] => Array
        (
            [0] => FeatureCollection
            [1] => FeatureCollection
        )

)

因为这是合并的两个源数组。

解决这个问题的一个简单方法是重新设置数组中的值,这段代码只是选择第一个值并将其设置为...

$op["type"] = $op["type"][0];
print_r($op);

会给...

Array
(
    [type] => FeatureCollection
)