使用PHP类结构生成JSON文档

时间:2016-08-25 11:30:01

标签: php json class

是否有人能够根据以下模板让我了解如何使用PHP类生成JSON结构

{
"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
    } ...
]......

}

我能够生成一个构造函数,它允许我使用$routes['Route 1'] = new Route[32.4,34.5]的方法实例化类,但我不确定如何为说{{1}生成额外的航点或Lat和Long元素无需重新实例化Route类。

2 个答案:

答案 0 :(得分:2)

您无需创建正式课程即可,只需使用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);

输出:

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

答案 1 :(得分:2)

这是一个将照顾你的json的课程:

<?php
Class Routes {

    private $routes = [];

    public function __construct($summary, $published){
        $this->routes['summary'] = $summary;
        $this->routes['published'] = $published;
    }

    public function addRoute($route){
        $this->routes[$route] = [];     
    }

    public function addWaypoint($route, $lat, $lon){
        $this->routes[$route][] = [
            "lat" => $lat,
            "long" => $lon
        ];
    }

    public function createJson(){
        return json_encode($this->routes);
    }

}

$routes = new Routes("A long route", true);
$routes->addRoute("Route 1");
$routes->addRoute("Route 2");
$routes->addWaypoint("Route 1", 23.4, 34.5);
$routes->addWaypoint("Route 1", 27.4, 384.5);
$routes->addWaypoint("Route 2", 25.4, 34.5);
$routes->addWaypoint("Route 2", 29.4, 384.5);

echo $routes->createJson();

返回此JSON:

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