TrueBlue TrueBlue - 3 months ago 11
PHP Question

Using PHP Class Structures to Generate JSON Documents

Is anyone able to give me an insight how to use PHP classes to generate a JSON structure based on the following template

{
"Summary": "A long route",
published": true,
"Route 1": [
{
"Lat": 23.4,
"Long": 34.5
},
{
"Lat": 27.4,
"Long": 384.5
} ...
]
"Route 2": [
{
"Lat": 25.4,
"Long": 34.5
},
{
"Lat": 29.4,
"Long": 384.5
} ...
]......


}

I am able to generate a constructor function that allows me to instantiate the classes using the method of
$routes['Route 1'] = new Route[32.4,34.5]
but I am not sure how to generate additional waypoints, or Lat and Long elements for a say
Route 1
, without re-instantiating the Route class.

Answer

You can do this without needing to create a formal class, but by simply using stdClass()

<?php

$json = new stdClass();
$json->summary = "A long route";
$json->published = true;

$routes = array();
$routes[] = array('Lat' => 23.4, 'Long' => 34.5);
$routes[] = array('Lat' => 27.4, 'Long' => 384.5);

$json->Route1 = $routes;

$routes = array();
$routes[] = array('Lat' => 11.4, 'Long' => 12.5);
$routes[] = array('Lat' => 12.4, 'Long' => 16.5);

$json->Route2 = $routes;

echo json_encode($json);

Output :

{
 "summary":"A long route",
 "published":true,
 "Route1":[{"Lat":23.4,"Long":34.5},
           {"Lat":27.4,"Long":384.5}
          ],
 "Route2":[{"Lat":11.4,"Long":12.5},
           {"Lat":12.4,"Long":16.5}
          ]
}