如何正确解码 php.ini 中同时包含数组和字符串的 geoJson? 我遇到的问题是从数据库读取它并转换回 json,坐标数组丢失。
我目前正在从(有效)geoJson.json 文件中读取它,并使用以下命令将其存储在 mysql 数据库中: $jsondata = json_decode($srcfile, true);效果很好 - 它在(mysql)数据库中看起来是正确的,并且仍然具有完整的坐标数组。
原始数据如下所示:(除了有 1000 个坐标)
{
"type": "Feature",
"geometry": {
"coordinates": [
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
],
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
]
],
"type": "MultiPolygon"
},
"properties": {
"prov_type": "province",
"prov_code": "24",
"prov_name_fr": "Qu\u00e9bec",
"geo_point_2d": [
53.3945173679,
-71.7823138976
],
"prov_name_en": "Quebec",
"year": "2019",
"prov_area_code": "CAN"
}
}
当我从数据库中提取它并对其运行 json_encode($data) 时,输出如下所示 - 缺少所有坐标。
{
"type":"Feature",
"geometry":{
"coordinates":,
"type":"MultiPolygon"
},
"properties":{
"prov_type":"province",
"prov_code":"35",
"prov_name_fr":"Ontario",
"geo_point_2d":[50.4486575765,-86.0470011166],
"prov_name_en":"Ontario",
"year":"2019",
"prov_area_code":"CAN"
}
}
或者
更新 - 添加了导入方法
public function importGeodata()
{
// $srcfile = file_get_contents('/var/www/vhosts/mcgill.local/src/core/components/mcgill/data/provinces.json');
$srcfile = file_get_contents('/var/www/vhosts/mcgill.local/src/core/components/mcgill/data/us-states.json');
$jsondata = json_decode($srcfile, true);
// echo '<pre>';print_r($jsondata); echo '</pre>';
foreach($jsondata['features'] as $feature)
{
// $search = $feature['properties']['prov_name_en']; // FOR CANADA
$search = $feature['properties']['NAME']; // FOR USA
if(!$updateObj = $this->modx->getObject('CatalogStates', array('name' => $search)))
{
echo '<br>Could not find object: ' . $search;
}else{
echo '<br>Found object: '.$search;
$updateObj->set('feature', json_encode(array($feature)));
if(!$updateObj->save())
{
echo '<br>Error saving object: ' . $search;
}
}
}
return;
}
检索数据:
public function getGeoJson()
{
$criteria = $this->modx->newQuery('CatalogStates');
$criteria->where([
'id:IN' => array(1,2),
]);
if($states = $this->modx->getCollection('CatalogStates',$criteria)) // returns an array of objects
{
foreach($states as $state)
{
$feature = $state->get('feature');
$coordinates = $feature['geometry']['coordinates'];
print_r($coordinates); // this returns the coordinates array
echo json_encode($coordinates); // this returns nothing!?
}
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
好吧,奇怪的是,MODX 搞砸了我...MODX 使用双方括号来表示应该处理或包含的代码 - 即
[[代码片段名称]] [[*include_chunk_name]]
等等
当它看到坐标结构时:
"coordinates": [ [ [ [ -64.59727115377405, 60.30061384178721 ], [ -64.52477086139639, 60.29980770242815 ] ] ], [ [ [ -64.59727115377405, 60.30061384178721 ], [ -64.52477086139639, 60.29980770242815 ] ] ] ]它基本上将其解释为:
"coordinates": [[ // try to run a code snip here // run this code snip (and fail) [[-64.59727115377405,60.30061384178721], // give up trying to output anything till we find a matching closing brace所以实际的解决方案是: