Json_encode behaves differently in arrayObject vs array ()

I had a function in 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); 

which outputs:

  "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" } } 

Now I rewrote the array to become such an object:

  //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); 

But this changes the output to:

  "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" } } } }, 

This makes it unusable as geoJSON for OpenLayers. Why does the json_encode function behave like this? Can I disable the installation of index numbers? Is this a possible small mistake?

+4
source share
3 answers

json_encode will display the same behavior with any object, even those that implement the ArrayAccess interface as an ArrayObject ; public properties are used.

To get the desired behavior, you must pass it the actual array, which can be obtained by calling ArrayObject::getArrayCopy() (or you can pass the object to an array).

 echo json_encode($newsensors->getArrayCopy()); 
+10
source

If I were to convert data trees containing ArrayObject at a different level, I wrote a code snippet to process and convert each ArrayObject before issuing json, hope this helps: https://github.com/nfroidure/Rest4/blob/master/php /class.Json.php

+2
source

Use the JsonSerializable Interface (PHP 5> = 5.4.0, PHP 7) and you should be safe:

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

Source: https://habr.com/ru/post/1308065/


All Articles