我不得不在PHP的函數:json_encode上ArrayObject的行爲不同VS陣列
//simple method with array()
$sensors = array();
$query = "select id, x(transform(wkb_geometry,". $epsg . ")) as lon, y(transform(wkb_geometry,". $epsg . ")) as lat from mytable;";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
while ($row = pg_fetch_assoc($result)) {
//var_dump($row);
$mySensor = new sensor($row['id'],$row['lat'],$row['lon']);
$sensors[] = $mySensor->geoJSON();
}
echo json_encode($sensors);
輸出:
"features": [{
"type": "Feature",
"id": 1579028,
"x": 4.85310557823,
"y": 52.7205622103,
"geometry": {
"type": "Point",
"coordinates": [4.85310557823, 52.7205622103],
"crs": {
"type": "OGC",
"properties": {
"urn": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
}
現在我已經重寫的陣列成爲這樣的對象:
//advanced method with arrayObject:
class sensors extends ArrayObject {
function __construct($epsg){
$query = "select id, x(transform(wkb_geometry,". $epsg . ")) as lon, y(transform(wkb_geometry,". $epsg . ")) as lat from mytable;";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
while ($row = pg_fetch_assoc($result)) {
//var_dump($row);
$mySensor = new sensor($row['id'],$row['lat'],$row['lon']);
$this[] = $mySensor->geoJSON();
}
}
}
$newsensors = new sensors($epsg);
echo echo json_encode($newsensors);
但這改變輸出到:
"features": {
"0": {
"type": "Feature",
"id": 1579028,
"x": 4.85310557823,
"y": 52.7205622103,
"geometry": {
"type": "Point",
"coordinates": [4.85310557823, 52.7205622103],
"crs": {
"type": "OGC",
"properties": {
"urn": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
}
}
},
這使得OpenLayers不能用作geoJSON。爲什麼json_encode函數的行爲如此?我可以關閉索引號的設置嗎?這是一個可能的小錯誤?
謝謝你這麼多salathe!您的解決方案適合我! – milovanderlinden 2010-04-27 21:47:15