如何正確解碼 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!? } } }
好吧,奇怪的是,MODX 搞砸了我...MODX 使用雙方括號來表示應該處理或包含的程式碼 - 即
[[程式碼片段名稱]] [[*include_chunk_name]]
等等
當它看到座標結構時:
它基本上將其解釋為:
所以實際的解決方案是: