4

我在php中有一个函数:

//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 函数会这样?我可以关闭索引号的设置吗?这是一个可能的小错误吗?

4

3 回答 3

11

json_encode将显示与任何对象相同的行为,即使是实现ArrayAccess接口的对象ArrayObject;使用公共属性。

要获得您想要的行为,您应该将其传递给可以通过调用检索的实际数组ArrayObject::getArrayCopy()(或者您可以将对象转换为数组)。

echo json_encode($newsensors->getArrayCopy());
于 2010-04-26T20:34:30.273 回答
2

必须在不同级别转换包含 ArrayObject 的数据树,所以我写了一段代码来处理和转换每个 ArrayObject 在输出 json 之前,希望它有所帮助: https ://github.com/nfroidure/Rest4/blob/master/php/类.json.php

于 2013-04-17T16:08:20.430 回答
1

使用JsonSerializable接口 (PHP 5 >= 5.4.0, PHP 7) 你应该是安全的:

public function jsonSerialize()
{
    return $this->getArrayCopy();
}
于 2016-07-02T10:37:39.620 回答