通过 PHP 将 json 格式化为 geojson

Formatting json to geojson via PHP

我正在尝试获取一些我从 mySQL 数据库调用的数据,以便以 GeoJSON 格式正确显示。这是我的一些 PHP 代码:

$data = array(); //setting up an empty PHP array for the data to go into

if($result = mysqli_query($db,$query)) {
  while ($row = mysqli_fetch_assoc($result))
  {
    $data[] = $row;
  }
}

$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$coordinates = array();
foreach($original_data as $key => $value) {
    $coordinates[] = array($value['latitude'], $value['longitude']);
}
$new_data = array(
    'type' => 'FeatureCollection',
    'features' => array(array(
        'type' => 'Feature',
    'properties' => array('time' => $value['time']),
    'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
    ),
    ),
);

$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);

到目前为止,我已经设法让我的结果看起来像这样:

但我需要它们看起来像这样,以便每组坐标都有自己的 "type" 和 "properties" 键值对:

我已经在这个问题上找到了一些帮助 here,但我就是无法克服最后一个格式化障碍...

您需要构建特征而不是构建坐标:

$data = array(); //setting up an empty PHP array for the data to go into

if($result = mysqli_query($db,$query)) {
  while ($row = mysqli_fetch_assoc($result))
  {
    $data[] = $row;
  }
}

$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$features = array();
foreach($original_data as $key => $value) {
    $features[] = array(
        'type' => 'Feature',
        'properties' => array('time' => $value['time']),
        'geometry' => array(
             'type' => 'Point', 
             'coordinates' => array(
                  $value['latitude'], 
                  $value['longitude'], 
                  1
             ),
         ),
    );
}
$new_data = array(
    'type' => 'FeatureCollection',
    'features' => $features,
);

$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);