2010-04-26 40 views
4

我不得不在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函數的行爲如此?我可以關閉索引號的設置嗎?這是一個可能的小錯誤?

回答

10

json_encode將顯示與任何對象相同的行爲,即使執行ArrayAccess接口的行爲也如ArrayObject所示;使用公共財產。

要獲得您想要的行爲,您應該通過調用ArrayObject::getArrayCopy()(或者您可以將對象轉換爲數組)來檢索實際數組。

echo json_encode($newsensors->getArrayCopy()); 
+0

謝謝你這麼多salathe!您的解決方案適合我! – milovanderlinden 2010-04-27 21:47:15

1

使用JsonSerializable接口( PHP 5> = 5.4.0,PHP 7),你應該安全:

public function jsonSerialize() 
{ 
    return $this->getArrayCopy(); 
}